二叉查找树的定义
二叉查找树:是一种特殊的二叉树,又叫排序二叉树,二叉排序树,二叉搜索树等等。
具体定义如下:
- 要么二叉查找树是一棵空树
- 要么二叉查找树由根结点、左子树、右子树组成,其中左子树和右子树都是二叉查找树,且左子树上所有结点的数据域均小于根结点的数据域,右子树上所有结点的数据域均大于根结点的数据域~
(左<根<右)
二叉查找树的基本操作(查找、插入、建树、删除)
搜索基本思路:
1. 如果当前根结点为NULL,那么查找失败,返回~
2. 如果要查找的值等于当前根结点的数据域,说明查找成功,访问~
3. 如果当前要查找的值小于当前根结点的数据,说明应该往左子树上找,向root->lchild递归~
4. 如果大于,则同理操作~
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 if(x > root->data)
search(root->rchild, x);
}
插入基本思路
对于一棵二叉查找树来说,查找某个数据的结点一定是按照确定的路径进行的~所以,当对某个需要查找的二叉查找树中查找成功,那么该结点已经存在,反之,如果这个地方需要查找的值在二叉查找树中查找失败,那么说明查找失败的地方就是需要插入的地方~所以,在root == NULL时新建需要插入的结点。显然插入的时间复杂度也是O(h),h为二叉查找树的高度~
void insert(node* root, int x){
if(root == NULL){
root = newNode(x);
return;
}
if(x == root->data)
return;
if(x < root->data)
insert(root->lchild, x);
if(x > root->data)
insert(root->rchild, x);
}
建树:与二叉树一模一样~
node* create(int data[], int n){
node* root = NULL;
for(int i = 0; i < n; i++){
insert(root, data[i]);
}
return root;
}
删除:
有两种做法,都是O(h),h为二叉查找树的高度~
详细内容:查看算法笔记P312~
绝对不是因为太长了懒得打字
寻找前驱代码~
//寻找以root为根结点的树的最大权值结点~
node* finMax(node* root){
while(root->rchild)
root = root->rchild;
}
寻找后继代码~
//寻找以root为根结点的树的最小权值结点~
node* finMin(node* root){
while(root->lchild)
root = root->lchild;
}
删除操作的基本思路~
假设决定用结点N的前驱P来替代N,替代之后在N的左子树中删除P。
基本思路如下~
- 如果当前结点root为空,说明不存在权值为给定权值x的结点,直接返回~
- 如果当前结点root的权值为给定的权值x,说明找到了想要删除的结点,此时进入删除处理~
a) 如果当前结点root不存在左右孩子,说明是叶子结点,直接删除即可~
b)根当前结点存在左孩子,那么在左子树中寻找结点前驱pre,然后让pre的数据覆盖root,然后在左子树中删除结点pre~
c) 如果当前结点root存在右孩子,那么在右子树中寻找结点后继next,然后让next的数据覆盖root,接着在右子树中删除结点next - 如果当前结点root的权值大于给定的权值x,则在左子树中递归删除权值为x的结点~
- 如果当前结点root的权值小于给定的权值x,则在右子树中递归删除权值为x的结点。
删除代码如下~
//删除以root为根结点的树中权值为x的结点~
void deleteNode(node* &root, int x){
if(root == NULL) return;
if(root->data == x){
if(root->lchild == NULL && root->rchild == NULL){
root == NULL;
}else if(root->lchild != NULL){
node* pre = finMax(root->lchild);
root->data = pre->data;
deleteNode(root->lchild, pre->data);
}else if(root->rchild != NULL){
node* next = finMin(root->rchild);
root->data = next->data;
deleteNode(root->rchild, next->data);
}
}else if(root->data > x){
deleteNode(root->lchild, x);
}else{
deleteNode(root->rchild, x);
}
}
二叉查找树的性质
对二叉搜索树进行中序遍历,遍历的结果是有序的~