BST简单测试

本文通过实践操作探讨了BST(二叉搜索树)的基础测试,强调理论知识必须结合实际动手才能深入理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

纸上得来终觉浅,绝知此事要躬行。

#include <iostream>
using namespace std;

struct node 
{
	int nt,val;
	node *r,*l;
};

void insert(int v , node *&t)
{
	if(t==NULL)
	{
		t=new node;
		if(t==NULL) cout<<" error "<<endl;
		else 
		{
			t->val=v,t->l=t->r=NULL;
		}
	}
	else if(v<t->val) insert(v,t->l);
	else if(v>t->val) insert(v,t->r);
}
node *find_min(node *t)
{
	if(t==NULL) return NULL;
	else if(t->l==NULL) return t;
	else   return find_min(t->l);
}
node *find_max(node *t)
{
	if(t==NULL) return NULL;
	else if(t->r==NULL) return t;
	else   return find_max(t->r);
}
void search(node *t)
{
	if(t!=NULL)
	{
		cout<<t->val<<endl;
		search(t->l);
		search(t->r);
	}
}
void delete_node(int v , node *&t)
{
	if(t==NULL) puts("error");

	else if(v<t->val) delete_node(v , t->l);
	else if(v>t->val) delete_node(v , t->r);
	else
	{
		int  te;
		node *p;
		if(t->l && t->r)
		{
			p=find_min(t->r);

			te=t->val;
			t->val=p->val;
			p->val=te;

			delete_node(v,t->r);
		}
		else 
		{
			p=t;
			if(t->l) t=t->l;
			else if(t->r) t=t->r;
			else t=NULL;
			delete p;
		}
	}
}
int main ()
{
	freopen("1.txt","r",stdin);
	node *R=new node;
	R->r=R->l=NULL;
	int v;
	node *p=R;
	for(int i=0 ;i<5 ; p=R , i++)
	{
		cin>>v;
		if(i==0)  R->val=v;
		else insert(v , p);
	}
	//

	p=R;
	p=find_min(p);
	cout<<"The min value:"<<p->val<<endl;

	p=R;
	p=find_max(p);
	cout<<"The max value:"<<p->val<<endl;

	p=R;
	cout<<"树的遍历:";
	search(p);
	cout<<endl;

	p=R;
	delete_node(7,p);

	p=R;
	cout<<"树的遍历:";
	search(p);
	cout<<endl;


	p=R;
	delete_node(45,p);

	p=R;
	cout<<"树的遍历:";
	search(p);
	cout<<endl;
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值