//二叉查找树的实现
struct Node
{
int data;
Node *lchild,*rchild,*parent;
};
//在以t为树根的二叉查找树中,递归查找关键字key
Node* recursion_tree_search(Node *t,int key)
{
if(t!=NULL || key==t->data)
return t;
if(key<t->data)
return recursion_tree_search(t->lchild,key);
else
return recursion_tree_search(t->rchild,key);
}
//在以t为树根的二叉查找树中,非递归查找关键字key
Node* iterative_tree_search(Node *t,int key)
{
while(t!=NULL && key!=t->data)
t=(key<t->data)?t->lchild:t->rchild;
return t;
}
//在以t为树根的二叉查找树中,查找最小元素,返回其指针
Node* tree_minimum(Node *t)
{
while(t->lchild!=NULL)
t=t->lchild;
return t;
}
//在以t为树根的二叉查找树中,查找最大元素,返回其指针
Node* tree_maxmum(Node *t)
{
while(t->rchild!=NULL)
t=t->rchild;
return t;
}
//查找x节点的直接后继,返回其指针
Mode* tree_successor(Node *x)
{
if(x->rchild!=NULL)
return tree_minimum(x->rchild);
else
{
Node *p=x->parent;
while(p!=NULL && x==p->rchild)
{
x=p;
p=p->parent;
}
return p;
}
}
//查找x结点的直接前驱,返回其指针
Node *tree_predecessor(Node *x)
{
if(x->lchild!=NULL)
return tree_maxmum(x->lchild);
else
{
Node *p=x->parent;
while(p!=NULL && x==p->lchild)
{
x=p;
p=p->parent;
}
return p;
}
}
//在以t为树根的二叉查找树中,插入结点
void tree_insert(Node *t,Node *x)
{
Node *p=NULL;
while(t!=NULL)
{
p=t;
if(x->data<t->data)
t=t->lchild;
else
t=t->rchild;
}
if(p==NULL)
t=x;
else if(x->data<p->data)
{
p->lchild=x;
x->parent=p;
}
else
{
p->rchild=x;
x->parent=p;
}
}
//在以t为树根的二叉查找树中,删除关键字为key的结点
Node* tree_delete(Node *t,int key)
{
Node *x=iterative_tree_search(t,key);//x指向被删除的真正结点
Node *y,*z;
if(x->lchild==NULL || x->rchild==NULL)
y=x;//y指向x
else
y=tree_successor(x);//y指向x的后继结点
if(y->lchild!=NULL)
z=y->lchild;//z指向被删除结点的左孩子
else
z=y->rchild;//z指向被删除结点的右孩子
if(z!=NULL)
z->parent=y->parent;//修改结点
if(y->parent==NULL)//y为根结点
t=z;
else if(y==y->parent->lchild)
y->parent->lchild=z;
else
y->parent->rchild=z;
if(y!=x)//y指向后继结点 交换
x->data=y->data;
return y;
}
二叉查找树
最新推荐文章于 2024-07-16 16:37:19 发布