#include<stdio.h>
struct Node
{
int key;
Node *p;
Node *left;
Node *right;
Node(int k = 0)
{
p=NULL;
left=NULL;
right=NULL;
key=k;
}
private:
Node& operator=(const Node&);
}*NIL;
struct Tree
{
Node *root;
Tree()
{
root = NIL;
}
};
//求最小值
Node* Minimum(Node *root)
{
while(root->left != NIL)
{
root = root->left;
}
return root;
}
//中序遍历
void InorderTreeWalk(const Node *root)
{
if(root != NIL)
{
InorderTreeWalk(root->left);
printf("%d ",root->key);
InorderTreeWalk(root->right);
}
}
//查询
Node* TreeSearch(const Tree *T,const int k)
{
Node *x=T->root;
while(x != NIL && x->key!=k)
{
if(x->key>k)
{
x = x->left;
}
else
{
x = x->right;
}
}
return x;
}
//插入
void TreeInsert(Tree *T, Node *z)
{
Node *y = NIL;
Node *x = T->root;
while (x != NIL)
{
y=x;
if(z->key < x->key)
{
x = x->left;
}
else
{
x = x->right;
}
}
z->p = y;
z->left = NIL;
z->right = NIL;
if(y == NIL)
{
T->root = z;
}
else
{
if(z->key < y->key)
{
y->left = z;
}
else
{
y->right = z;
}
}
}
//交换子树
void Transplant(Tree *T,Node *u,Node* v)
{
if(u->p == NIL)
{
T->root = v;
}
else
{
if(u == u->p->left)
{
u->p->left = v;
}
else
{
u->p->right = v;
}
}
if(v != NIL)
{
v->p = u->p;
}
}
//删除
void TreeDelete(Tree *T, Node *z)
{
if(z->left == NIL)
{
Transplant(T,z,z->right);
}
else if(z->right == NIL)
{
Transplant(T,z,z->left);
}
else
{
Node *y = Minimum(z->right);
if(y!=z->right)
{
Transplant(T,y,y->right);
y->right = z->right;
z->right->p = y;
}
Transplant(T,z,y);
y->left = z->left;
z->left->p = y;
}
}
int main()
{
Tree T;
for(int i=10;i>9;i--)
{
TreeInsert(&T,new Node(i));
}
InorderTreeWalk(T.root);
printf("\n");
Node *temp;
Node Temp;
if((temp = TreeSearch(&T,5)) != NIL)
{
printf("find 5\n");
TreeDelete(&T,temp);
printf("Delete 5\n");
}
InorderTreeWalk(T.root);
printf("\n");
/*
if(TreeSearch(&T,0) == NIL)
{
printf("do not find 0\n");
}
*/
return 0;
}