二叉排序树中的元素添加、删除

二叉排序树的元素添加比较简单,把元素输入的函数拿来即用。

二叉排序树的元素删除比较复杂,需要考虑要删除的元素是否有左子树、右子树。这里mark一下自己的个人习惯,会把root节点重新返回(其实函数中的操作会自动在root上进行,不需要返回,root也会发生变化,自己属于多此一举)。

该程序的元素删除函数拥有最基本的删除操作,考虑的情况极少,比如二叉树中没有该元素等。该程序还有一个bug,第一个节点无法删除。。。

#include<iostream>
using namespace std;

struct node
{
	int data;
	node *left;
	node *right;
	node(){left=NULL;right=NULL;};
};

node *insert(node *root,int a)
{
	if(root==NULL)
	{
		root=new node;
		root->data=a;
		return root;
	}
	else if(a<root->data)
	root->left=insert(root->left,a);
	else if(a>root->data)
	root->right=insert(root->right,a);
	
	return root; 
}

void preorder(node *root)
{
	if(root)
	{
		cout<<root->data<<" ";
		preorder(root->left);
		preorder(root->right); 
	}
}

void inorder(node *root)
{
	if(root)
	{
		inorder(root->left);
		cout<<root->data<<" ";
		inorder(root->right); 
	}
}

void postorder(node *root)
{
	if(root)
	{
		postorder(root->left);
		postorder(root->right);
		cout<<root->data<<" ";
	}
}

node *deletenode(node *root,int a)
{
	node *p,*q,*s,*f;
	p=root;
	f=NULL;
	//得到要删除的节点p及其父节点f
	while(p&&p->data!=a)
	{
		f=p;
		if(a<p->data)
		p=p->left;
		else
		p=p->right;
	}
	if(p->left==NULL)
	{
		if(f==NULL)
		root=p->right;
		else if(f->left==p)
		f->left=p->right;
		else
		f->right=p->right;
		delete p;
	} 
	else
	{
	 	q=p;
	 	s=p->left;
		while(s->right)
		{
			q=s;
			s=s->right;
		} 
		if(q==p)
		q->left=s->left;
		else
		q->right=s->left;
		p->data=s->data;
		delete s; 
	}
	return root;
 } 

int main()
{
	node *root;
	root=NULL;
	int n;
	cin>>n;
	int a;
	for(int i=0;i<n;i++)
	{
		cin>>a;
		root=insert(root,a);
	}
	cout<<endl;
	cout<<"先序遍历:"; 
	preorder(root);
	cout<<endl;
	cout<<"中序遍历:";
	inorder(root);
	cout<<endl;
	cout<<"后序遍历:";
	postorder(root);
	cout<<endl;
	
	cout<<"请插入一个数:";
	int b;
	cin>>b;
	insert(root,b);
	cout<<"中序遍历:";
	inorder(root);
	cout<<endl;
	
	while (1) 
	{
		cout<<"请删除一个数:";
		int c;
		cin>>c;
		root=deletenode(root,c);
		cout<<"中序遍历:";
		inorder(root);
		cout<<endl;
	} 
	
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值