二叉排序树的元素添加比较简单,把元素输入的函数拿来即用。
二叉排序树的元素删除比较复杂,需要考虑要删除的元素是否有左子树、右子树。这里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;
}