#include <iostream>
#include <vector>
using namespace std;
typedef struct Tree {
int key;
Tree *left;
Tree *right;
Tree *parent;
}Tree;
void TreeInsert(Tree *&root, Tree *&z)
{
Tree *y = NULL;
Tree *x = root;
while(x != NULL)
{
y = x;
if(z->key < x->key)
x = x->left;
else
x = x->right;
}
z->parent = y;
if(y == NULL)
{
root = z;
}
else if(z->key < y->key)
{
y->left = z;
}
else
{
y->right = z;
}
}
void createSerachTree(Tree *&root, vector<int> nums)
{
for(vector<int>::iterator it = nums.begin(); it != nums.end(); it ++)
{
Tree *z = new Tree;
z->key = *it;
z->left = NULL;
z->right = NULL;
z->parent = NULL;
TreeInsert(root, z);
}
}
Tree *TreeMinimum(Tree *x)
{
while(x->left != NULL)
{
x = x->left;
}
return x;
}
Tree *TreeMaximum(Tree *x)
{
while(x != NULL)
x = x->right;
return x;
}
Tree *TreePredecesor(Tree *x)
{
Tree *y;
if(x->left != NULL)
return TreeMaximum(x->left);
y = x->parent;
while(y != NULL && x == y->left)
{
x = y;
y = y->parent;
}
return y;
}
Tree *TreeSuccessor(Tree *x)
{
Tree *y;
if(x->right != NULL)
return TreeMinimum(x->right);
y = x->parent;
while(y != NULL && x == y->right)
{
x = y;
y = y->parent;
}
return y;
}
void TransPlant(Tree *&root, Tree *&u, Tree*&v)
{
if(u->parent == NULL)
{
root = v;
}
else if(u == u->parent->left)
{
u->parent->left = v;
}
else
{
u->parent->right = v;
}
}
void TreeDelete(Tree *&root, Tree *&z)
{
Tree *tmp1, *tmp2;
if(z->left == NULL)
{
tmp1 = z;
TransPlant(root, z, z->right);
delete tmp1;
}
else if(z->right == NULL)
{
tmp1 = z;
TransPlant(root, z, z->left);
delete tmp1;
}
else
{
Tree *y;
y = TreeMinimum(z->right);
if(y->parent != z)
{
tmp2 = y;
TransPlant(root, y, y->right);
y->right = z->right;
y->right->parent = y;
delete tmp2;
}
tmp1 = z;
TransPlant(root, z, y);
y->left = z->left;
y->left->parent = y;
delete tmp1;
}
}
Tree *TreeSearch(Tree *x, int key)
{
while(x != NULL && key != x->key)
{
if(key < x->key)
x = x->left;
else
x = x->right;
}
return x;
}
void InOderShow(Tree *root)
{
if(root != NULL)
{
InOderShow(root->left);
cout << "T " << root->key << endl;
InOderShow(root->right);
}
}
int main()
{
Tree *root, *z, *y;
root = NULL;
vector<int> nums{12, 5, 18, 2, 9, 15, 19, 13, 17};
createSerachTree(root, nums);
z = TreeSearch(root, 13);
TreeDelete(root, z);
z = TreeSearch(root, 9);
y = TreePredecesor(z);
cout << "前驱 " << y->key << endl;
z = TreeSearch(root, 9);
y = TreeSuccessor(z);
cout << "后继 " << y->key << endl;
cout << "树根 " << root->key << endl;
InOderShow(root);
return 0;
}