数据结构-二叉查找树BST

一、二叉查找树的定义

  • 是一种特殊的二叉树,又称排序二叉树,二叉搜索树,二叉排序树。
  1. 递归定义如下:
  2. 要么二叉树查找树是一棵空树
  3. 要么二叉树查找树由根结点、左子树、右子树组成,其中左子树和右子树都是二叉树查找树,且左子树上所有结点的数据域均小于或等于根结点的数据域,右子树上所有结点的数据域均大于根结点的数据域。

二、二叉查找树的基本操作

1.查找操作

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.插入操作

//注意参数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.二叉查找树的建立

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

4.二叉查找树的删除

//寻找以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
    }
}

三、二叉查找树的性质

  1. 对二叉查找树进行中序遍历,遍历的结果是有序的

猜你喜欢

转载自www.cnblogs.com/tsruixi/p/12331864.html