二叉搜索树的基本操作

建立一个非负二叉搜索树(-1表空结点),编写查找函数,层序遍历函数,插入函数,删除函数,查找最大值最小值函数

输入该树和要查找的值

输出:

如果找到,打印出

x is found

没找到打印出 Not found

打印出层序遍历序列

删除最大值和最小值

删除成功输出

x is delete

最后再进行一层序遍历

例如:


输入样例:

8 5 3 -1 4 -1 -1 7 -1 -1 15 11 10 -1 -1 12 -1 -1 16 -1 -1

输出样例:

input what you want to find: 4
4 is found
levelorder: 8 5 15 3 7 11 16 4 10 12
16 is delete
3 is delete
levelorder: 8 5 15 4 7 11 10 12

#include <iostream> 
#include <algorithm>
#include <queue> 
using namespace std;
typedef struct bstnode* pbst;
queue<pbst> q;
struct bstnode
{
	int data;
	pbst left,right;
}*root;

pbst insert(int x,pbst t)//插入
{
	if(!t)
	{
		t=new bstnode;
		t->data=x;
		t->left=t->right=NULL;
	}
	else 
		if(x>t->data)
			t->right=insert(x,t->right);
		else
			t->left=insert(x,t->left);
	return t; 
}

pbst creat(pbst t)//建树
{
	int tmp;
	cin>>tmp;
	if(tmp==-1)
		t=NULL;
	else
	{
		t=insert(tmp,t);
		t->left=creat(t->left);
		t->right=creat(t->right); 
	}
	return t;
}

pbst Find(pbst t,int x)//查找
{
	while(t)
	{
		if(x>t->data)
			t=t->right;
		else if(x<t->data)
			t=t->left;
		else
			return t;
	}
	return NULL;
}
pbst  Findmin(pbst t)//找最小值
{
	if(t)
		while(t->left)
			t=t->left;
	return t;
}
pbst Findmax(pbst t)//找最大值
{
	if(t)
		while(t->right)
			t=t->right;
	return t;
}
pbst Del(int x,pbst t)//删除
{
	pbst tmp;
	if(t)
	{
		if(x>t->data)
			t->right=Del(x,t->right);
		else if(x<t->data)
			t->left=Del(x,t->left);
		else
			if(t->left&&t->right)
			{
				tmp=Findmin(t->right);
				t->data=tmp->data;
				t->right=Del(tmp->data,t->right);
			}
			else
			{
				tmp=t;
				if(!t->left)
					t=t->right;
				else if(!t->right)
					t=t->left;
				free(tmp);
			}
	}
	return t;
}

void levelorder(pbst t)//层序遍历
{
	pbst tmp;
	if(t)
	{
		q.push(t);
		while(!q.empty())
		{
			tmp=q.front();
			cout<<tmp->data<<" ";
		    q.pop();
		    if(tmp->left)
				q.push(tmp->left);
			if(tmp->right)
				q.push(tmp->right);	
		}
	}
}


int main() {
	int n;
	pbst t;
	root=creat(root);
	cout<<"input what you want to find: "; 
	cin>>n;
	t=Find(root,n);
	if(t)
		cout<<t->data<<" is found"<<endl;
	else
		cout<<"Not found"<<endl;
	cout<<"levelorder: "; 
	levelorder(root);
	cout<<endl;
	t=Findmax(root);
	cout<<t->data<<" is delete"<<endl;
	root=Del(t->data,root);
	t=Findmin(root);
	cout<<t->data<<" is delete"<<endl;
	root=Del(t->data,root);
	cout<<"levelorder: "; 
	levelorder(root);
	cout<<endl;	
	return 0;  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值