您的位置:首页 > 其它

算法导论笔记之----二叉搜索树的插入、删除、搜索操作

2012-07-24 08:15 363 查看

#include<iostream>
using namespace std;
struct tree
{
int Key;
tree *left;
tree *right;
};
void SetNull(tree *&Root,int x);
void Insert(tree *&Root,int x)
{
if(Root==NULL)
{
Root=new tree;
Root->Key=x;
Root->left =Root->right=NULL;
return ;
}
else
{
if(Root->Key<x)
Insert(Root->right ,x);
else
Insert(Root->left,x);
}
return ;
}
//在2叉树中搜索某个元素
bool Find ( tree *&Root,const int& x)
{
if(Root==NULL)
return false;
else
if(Root->Key==x)
return true;
else
{
if(Root->Key<x)
Find(Root->right,x);
else
Find(Root->left,x);
}
}
//寻找某个元素的位置
tree *find(tree *Root,const int &x)
{
if(Root->Key==x)
return Root;
else
{
if(x<Root->Key)
find(Root->left,x);
else
find(Root->right,x);
}
}
//有一个孩子为空
void Delete1(tree *&Root,const int &x)
{
Root->left ==NULL?Root=Root->right:Root=Root->left;
}
//都为空
void Delete2(tree *&Root,const int &x)
{
Root=NULL;
}
//左右孩子都不为空时
void Delete3(tree *&Root,const int &x)
{
tree *node=new tree;
node=Root->right;
while(node->left!=NULL)
node=node->left;
SetNull(Root->right ,node->Key);
Root->Key=node->Key;
}
//删除某一个节点
void Delete (tree *&Root,const int &x)
{
if(Root->Key==x)
{
if(Root->left!=NULL&&Root->right!=NULL)
Delete3(Root,x);
else
if(Root->left==NULL&&Root->right==NULL)
Delete2(Root,x);
else
Delete1(Root,x);
}
else
if(Root->Key<x)
Delete(Root->right ,x);
else
Delete(Root->left,x);
}
//将某个节点设置为空
void SetNull(tree *&Root,int x)
{
if(Root->Key==x)
Root=NULL;
else
if(Root->Key<x)
SetNull(Root->right ,x);
else
SetNull(Root->left,x);
}
int main()
{
int x;
tree *Root;
Root=NULL;
while(cin>>x,x)
Insert(Root,x);
cin>>x;
Delete(Root,x);
return 0;
}
//20 10 30 5 15 25 35 3 8 12 17 1 4 6 9

在删除操作中处理第三种情况采用算法导论中所描述的,直接将要删除的节点用改节点后继替代,同时将后继清空。例如图中5的后继为6,10的前继为9.。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 tree delete null insert
相关文章推荐