二叉搜索树的实现

#include<iostream>
using namespace std;
//二叉搜索树左儿子的值比当前节点小,右儿子的数值比当前节点大
struct node
{
	int val;
	node *lchd,*rchd;
};
//创建树
node *insert(node *p,int x)
{
	if(p==NULL)
	{
		node* q=new node;
		q->val=x;
		q->lchd=q->rchd=NULL;
		return q;
	}
	else
	{
		if(x<p->val) p->lchd=insert(p->lchd,x);
		else p->rchd=insert(p->rchd,x);
	}
	return p;
}
//查找
bool find(node* p,int x)
{
	if(p==NULL) return false;
	else if(x==p->val) 
		return true;
	else if(x<p->val) 
	{
		return find(p->lchd,x);
	}
	else return find(p->rchd,x);
}
//删除数值
node *remove(node* p,int x)
{
	//需要删除的节点没有左儿子,那么就把右儿子提上去
	//需要删除的节点的左儿子没有右儿子,那么就把左儿子提上去
	//以上两种情况都不满足,就把左儿子的子孙中最大的节点提到需要删除的节点上
	if(p==NULL) return NULL;
	else if(x<p->val) p->lchd=remove(p->lchd,x);
	else if(x>p->val) p->rchd=remove(p->rchd,x);
	else if(p->lchd==NULL)
	{
		node* q=p->rchd;
		delete p;
		return q;
	}
	else if(p->lchd->rchd==NULL)
	{
		node *q=p->lchd;
		q->rchd=p->rchd;
		delete p;
		return q;
	}
	else 
	{
		node* q;
		for(q=p->lchd;q->rchd->rchd!=NULL;q=q->rchd);
		node* r=q->rchd;
		q->rchd=r->rchd;
		r->lchd=p->lchd;
		r->rchd=p->rchd;
		delete p;
		return r;
	}
	return p;
}
void print(node* p)//中序遍历
{
	if(p==NULL) 
		return ;
	print(p->lchd);
	cout<<p->val<<" ";
	print(p->rchd);
}
void releaseTree(node* p)//释放整棵树
{
	if(p==NULL) return;
	releaseTree(p->lchd);
	releaseTree(p->rchd);
	delete p;
}
int main()
{
	int a[12]={1,7,90,32,44,31,22,10,20,13,433,21};
	node* root=NULL;
	for(int i=0;i<12;i++)
	{
		root=insert(root,a[i]);
	}
	cout<<"the tree before delele:";
	print(root);
	cout<<endl;
	if(find(root,21))
	cout<<"the number "<<21<<"does exist!!"<<endl;
	else cout<<"the number "<<21<<" does not exist!!"<<endl;
	remove(root,21);

	cout<<"the tree after delele:";
	print(root);
	cout<<endl;

	if(find(root,21))
		cout<<"the number "<<21<<"does exist!!"<<endl;
	else cout<<"the number "<<21<<" does not exist!!"<<endl;
	system("pause");

	releaseTree(root);//释放节点
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值