您的位置:首页 > 理论基础 > 数据结构算法

《数据结构与算法分析》--二叉查找树

2017-01-17 20:39 78 查看
二叉查找树的结构:

struct TreeNode
{
ElementType element;
TreeNode* left;
TreeNode* right;
};
typedef TreeNode* SearchTree;
typedef TreeNode* position;


二叉查找树的操作声明:

//清空树
SearchTree MakeEmpty(SearchTree t)
{
if(t!=NULL)
{
MakeEmpty(t->left);
MakeEmpty(t->right);
free(t);
}
return NULL;
}
//插入操作
position Insert(ElementType x,SearchTree t)
{
if(t==NULL)
{
t=new TreeNode;
t->element=x;
t->left=t->right=NULL;
}
else
{
if(x < t->element)
{
t->left=Insert(x,t->left);//左子树指向左儿子
}
if(x > t->element)
{
t->right=Insert(x,t->right);//右子树指向右儿子
}
}
return t;//返回的是根节点的地址
}
//删除操作
position Delete(ElementType x,SearchTree t)
{
position tmp;
if(t==NULL)
return NULL;
else if(x < t->element)
{
t->left=Delete(x,t->left);
}
else if(x > t->element)
{
t->right=Delete(x,t->right);
}
else if(t->left && t->right)
{
temp=FindMin(t->left);
t->element=temp->element;
t->right=Delete(t->element,t->right);
}
else
{
temp=t;
if(t->left==NULL)
t=t->right;
if(t->right==NULL)
t=t->left;
free(temp);
}
return t;
}
//查找操作
position Find(ElementType x,SearchTree t)
{
if(t==NULL)
return NULL;
else if(x < t->element)
{
return Find(x,t->left);
}
else if(x > t->element)
{
return Find(x,t->right);
}
else
return t;
}
//查找最大值操作
position FindMax(SearchTree t)
{
if(t==NULL)
return NULL;
else if(t->right!=NULL)
return FindMax(t->right);
else
return t;
}
//查找最小值操作
position FindMin(SearchTree t)
{
if(t==NULL)
return NULL;
else if(t->left!=NULL)
return FindMin(t->left);
else
return t;
}


二叉查找树相对来说比较简单,操作较少。在上述操作中,最难的是Delete操作,Delete操作一定要分为四种情况。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐