二叉查找树(BST)

二叉查找树的定义

二叉查找树:是一种特殊的二叉树,又叫排序二叉树,二叉排序树,二叉搜索树等等。
具体定义如下:

  1. 要么二叉查找树是一棵空树
  2. 要么二叉查找树由根结点、左子树、右子树组成,其中左子树和右子树都是二叉查找树,且左子树上所有结点的数据域均小于根结点的数据域,右子树上所有结点的数据域均大于根结点的数据域~
    (左<根<右)

二叉查找树的基本操作(查找、插入、建树、删除)

搜索基本思路:
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。
基本思路如下~

  1. 如果当前结点root为空,说明不存在权值为给定权值x的结点,直接返回~
  2. 如果当前结点root的权值为给定的权值x,说明找到了想要删除的结点,此时进入删除处理~
    a) 如果当前结点root不存在左右孩子,说明是叶子结点,直接删除即可~
    b)根当前结点存在左孩子,那么在左子树中寻找结点前驱pre,然后让pre的数据覆盖root,然后在左子树中删除结点pre~
    c) 如果当前结点root存在右孩子,那么在右子树中寻找结点后继next,然后让next的数据覆盖root,接着在右子树中删除结点next
  3. 如果当前结点root的权值大于给定的权值x,则在左子树中递归删除权值为x的结点~
  4. 如果当前结点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);
	}
}

二叉查找树的性质

对二叉搜索树进行中序遍历,遍历的结果是有序的~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

艾尔伯特想变瘦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值