#include <iostream>
using namespace std;
typedef struct Node //树结点定义
{
int key;
Node *lchild, *rchild, *parent;
}Node, *BSTree;
Node * BSTreeSearch(BSTree T, int k) //遍历查找
{
if(T == NULL || k == T->key)
return T;
if(k < T->key)
return BSTreeSearch(T->lchild, k);
else
return BSTreeSearch(T->rchild, k);
}
Node * IterativeBSTreeSearch(BSTree T, int k) //遍历查找的非递归版本
{
while(T != NULL && k != T->key)
{
if(k < T->lchild->key)
T = T->lchild;
else
T = T->rchild;
}
return T;
}
Node * BSTreeMinimum(BSTree T) //最小值
{
while(T->lchild != NULL)
T = T->lchild;
return T;
}
Node * BSTreeMaximum(BSTree T) //最大值
{
while(T->rchild != NULL)
T = T->rchild;
return T;
}
Node *BSTreeSuccessor(Node *x) //结点x的中序后续结点
{
if(x->rchild != NULL)
return BSTreeMinimum(x->rchild);
Node *y = x->parent;
while(y != NULL && x == y->rchild)
{
x = y;
y = y->parent;
}
return y;
}
void BSTreeInsert(BSTree &T, int k) //插入,注意BSTree作为引用型指针参数的作用,可以直接传值
{
Node *y = NULL;
Node *x = T;
Node *z = new Node;
z->key = k;
z->lchild = z->parent = z->rchild = NULL;
while(x != NULL)
{
y = x;
if(k < x->key)
x = x->lchild;
else
x = x->rchild;
}
z->parent = y;
if(y == NULL)
{
T = z;
}
else
if(k < y->key)
y->lchild = z;
else
y->rchild = z;
}
Node* BSTreeDelete(BSTree &T, Node *z) //删除节点z
{
Node *x, *y;
// z是要删除的节点,而y是要替换z的节点
if(z->lchild == NULL || z->rchild == NULL)
y = z; // 当要删除的z至多有一个子树,则y=z;
else
y = BSTreeSuccessor(z); // y是z的后继
if(y->lchild != NULL)
x = y->lchild;
else
x = y->rchild; //注意,x最多只有一个子树
if(x != NULL)
x->parent = y->parent;
if(y->parent == NULL)
T = x;
else if(y == y->parent->lchild)
y->parent->lchild = x;
else
y->parent->rchild = x;
if(y != z) //y=z的情况是z只有1个子树的情况
z->key = y->key;
return y;
}
void InBSTree(BSTree T)
{
if(T != NULL)
{
InBSTree(T->lchild);
cout << T->key << " ";
InBSTree(T->rchild);
}
}
int main()
{
int m;
BSTree T = NULL;
for(int i=0; i<6; ++i)
{
cin >> m;
BSTreeInsert(T, m);
cout << "二叉查找树中序查找:";
InBSTree(T);
cout << endl;
}
cout << "删除根节点后:";
BSTreeDelete(T, T);
InBSTree(T);
}
12 二叉查找树
最新推荐文章于 2023-09-17 08:57:12 发布