Data structures - binary search tree BST

The definition of a binary search tree

  • It is a special kind of binary tree, also known as binary tree sort, binary search trees, binary sort tree.
  1. Recursively defined as follows:
  2. Either binary search tree is empty tree
  3. Either by the binary search tree root, left subtree, right subtree, where the left and right subtree is the subtree binary search tree, the tree and the left sub-data fields of all nodes are equal to or less than the root data field, the data field all the right subtree of the root node is greater than the data fields.

Basic Operation Second, the binary search tree

1. Find operation

void search(node* root, int x){
    if(root == NULL){
        printf("search failed\n");
        return;
    }
    if(x == root->data){
        printf("%d\n", root->data);
    }else if(x < root->data){
        search(root->lchild, x);
    }else{
        search(root->rchild, x);
    }
}

2. insert

//注意参数root要加引用&
void insert(node* &root, int x){
    if(root == NULL){
        root = newNode(x);
        return;
    }
    if(x == root->data){
        return;
    }else if(x < root->data){
        insert(root->lchild, x);
    }else{
        insert(root->rchild, x);
    }
}

3. The establishment of a binary search tree

node* Create(int data[], int n){
    node* root = NULL;
    for(int i = 0; i < n; i++){
        insert(root, data[i]);
    }
    return root;
}

4. binary search tree deletion

//寻找以root为根结点的树中最大权值结点
node* findMax(node* root){
    while(root->rchild != NULL){
        root = root->rchild;
    }
    return root;
}

//以寻找root为根结点的树中最小权值结点
node* findMin(node* root){
    while(root->lchild){
        root = root->lchild;
    }
    return root;
}

//删除以root为根结点的树中权值为x的结点
void deleteNode(node* &root, int x){
    if(root == NULL) return;//不存在权值为x的结点
    if(root->data == x){
        if(root->lchild == NULL && root->rchild == NULL){//叶子结点直接删除
            root = NULL;//把root地址设为NULL,父结点就引用不到它了
        }else if(root->lchild != NULL){//左子树不为空时
            node* pre = findMax(root->lchild);//找到root的前驱结点
            root->data = pre->data;//用前驱结点覆盖root
            deleteNode(root->lchild, pre->data);//在左子树中删除结点pre
        }else{//右子树不为空
            node* next = findMin(root->rchild);//找到root后继
            root->data = next->data;//用后继结点覆盖root
            deleteNode(root->rchild, next->data);//在右子树中删除结点next
        }
    }else if(root->data > x){
        deleteNode(root->lchild, x);//在左子树中删除x
    }else{
        deleteNode(root->rchild, x);//在右子树中删除x
    }
}

Third, the nature of a binary search tree

  1. On a binary search tree in order traversal, traversing the result is ordered

Guess you like

Origin www.cnblogs.com/tsruixi/p/12331864.html