今天写一写二叉搜索树的插入,查找,删除的操作。
首先给出节点的数据结构
struct node
{
int data;
node*l;
node* r;
};
第一个是查找操作:
void search(node* root,int x)
{
if(root==NULL)
{
printf("no");
return;
}
if(root->data==x)
{
printf("yes");
return;
}
if(x<root->data)
search(root->l,x);
else
search(root->r,x);
}
第二个插入操作:
void insert(node* &root,int x)
{
if(root==NULL)
{
root=new node;
root->data=x;
return ;
}
if(root->data==x)
return;
if(x<root->data)
insert(root->l,x);
else
insert(root->r,x);
}
第三是删除操作:
这里要说明的是,实际上删除的操作有很多的实现的方式,有递归和非递归的,这里用了递归,是因为实现简单,不易出错,容易在考场和比赛是写出。
node* findPre(node* root)
{
while(root->r!=NULL)
root=root->r;
return root;
}
node*findPost(node* root)
{
while(root->l!=NULL)
root=root->l;
return root;
}
bool deletee(node* root,int x)
{
if(root==NULL)
return false;
if(root->data==x)
{
if(root->l==NULL&&root->r==NULL)
{
root=NULL;
return true;
}
else
{
if(root->l!=NULL)
{
node* pre=findPre(root->l);
root->data=pre->data;
deletee(root->l,pre->data);
}
else
{
node* post=findPost(root->r);
root->data=post->data;
deletee(root->r,post->data);
}
}
}
else
{
if(x<root->data)
deletee(root->l,x);
else
deletee(root->r,x);
}
}
基本上就这些,但是没有用数据测试过,但是大致思路上就这样了。