15.6 二叉排序树删除实战

代码实战步骤:

在原有二叉树排序树建树,查找的基础上,新增了二叉排序树删除。二叉排序树的删除我们使用递归来实现,理解代码时可以结合Binary Search Tree Visualization (usfca.edu)动画网站。 

#include <stdio.h>
#include <stdlib.h>
typedef int KeyType;
typedef struct BSTNode{
	KeyType key;
	struct BSTNode *lchild, *rchild;
}BSTNode, *BiTree;
int BST_Insert(BiTree &T,KeyType k)
{
	BiTree TreeNew=(BiTree)calloc(1,sizeof(BSTNode));//新结点申请空间
	TreeNew->key=k;//把值放入
	if(NULL==T){
		T=TreeNew;
		return 1;//代表插入成功
	}
	BiTree p=T,parent;//p用来查找树
	while(p){
		parent=p;//parent用来存p的父亲
		if(k>p->key){
			p=p->rchild;
		}else if(k<p->key){
			p=p->lchild;
		}else{
			return -1;//相等元素不可放入查找树,考研不会考相等元素放入问题
		}
	}
	//接下来要判断放到父亲的左边还是右边
	if(k>parent->key){
		parent->rchild=TreeNew;
	}else{
		parent->lchild=TreeNew;
	}
	return 1;
}
void Creat_BST(BiTree &T,KeyType str[],int n)
{
	for(int i=0;i<n;i++){
		BST_Insert(T,str[i]);//把某一个结点放入二叉查找树
	}
}
BiTree BST_Search(BiTree T,KeyType key,BiTree &p)
{
	p = NULL;//存储父亲结点的地址值
	while(T!=NULL&&key!=T->key){
		p=T;
		if(key<T->key)
			T=T->lchild;
		else
			T=T->rchild;
	}
	return T;
}
void InOrder(BiTree T)//中序遍历二叉排序树
{
	if(T!=NULL){
		InOrder(T->lchild);
		printf("%3d",T->key);
		InOrder(T->rchild);
	}
}
void DeleteNode(BiTree &root,KeyType x)//通过递归实现结点删除
{
	if(root == NULL)	//如果没找到
		return;
	if(x<root->key){
		DeleteNode(root->lchild,x);//往左子树找要删除的结点
	}else if(x>root->key){
		DeleteNode(root->rchild,x);//往右子树找要删除的结点
	}else{ //查找到了删除结点
		if(root->lchild == NULL){ //左子树为空,右子树直接顶上去
			BiTree tempNode = root;//用临时的存着的目的是一会要free
			root = root->rchild;
			free(tempNode);
		}else if(root->rchild == NULL){ //右子树为空,左子树直接顶上去
			BiTree tempNode = root;//临时指针
			root = root->lchild;
			free(tempNode);
		}else{ //左右子树都不为空
			   //一般的删除策略是左子树的最大数据 或 右子树的最小数据 代替要删除的结点
			   //这里采用查找左子树最大数据来代替
			   BiTree tempNode = root->lchild;
			   while(tempNode->rchild!=NULL){ //向右找到最大的
			   		tempNode = tempNode->rchild;
			   }
			   root->key = tempNode->key;//把tempNode对应的值替换到要删除的值的位置上
			   DeleteNode(root->lchild,tempNode->key);//删除tempNode			   
		}
	}
	
}

int main()
{
	BiTree T = NULL;//树根
	BiTree parent;//存储父亲结点的值
	BiTree search;
	KeyType str[7] = {54,20,66,40,28,79,58};
	Creat_BST(T,str,7);
	InOrder(T);
	printf("\n");
	search=BST_Search(T,40,parent);
	if(search){
		printf("找到对应结点值,值=%d\n",search->key);
	}else{
		printf("未找到对应结点\n");//没找到search返回的是NULL
	}
	DeleteNode(T,40);//删除结点
	InOrder(T);
	printf("\n");
	return 0;
}
 20 28 40 54 58 66 79
找到对应结点值,值=40
 20 28 54 58 66 79

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值