(1)定义一个链表式结构体,作为bst的节点node,key值为int(注意不要用string类作为后续red-black tree的color,?为什么不清楚?)
typedef struct node{
int key; /*int color;*/
struct node *left; struct node *right; struct node *p;
}*pnode, node;
(2)定义一个sentinel作为所有空指针:
pnode nil = NULL;
(3)首先定义tree_insert,参数为bst的根节点root,以及待插入的节点z,注意z作为一个待插入节点其children均为空指针
void tree_insert(pnode &root, pnode z){
if(root != nil){
pnode y = nil;
pnode x = root;
while(x != nil){
y = x;
if(x->key > z->key)
x = x->left;
else
x = x->right;
}
z->p = y;
if(z->key > y->key)
y->right = z;
else
y->left = z;
}
else{
root = (pnode)malloc(sizeof(node));
z->p = nil;
root = z;
}
}
(4)递归实现中序遍历inorder_walk
void inorder_walk(pnode x){
if(x != nil){
inorder_walk(x->left);
cout<<x->key<<" ";
inorder_walk(x->right);
}
}
(5)search某key值得节点
pnode search(pnode x, int key){
if(x != nil){
if(x->key == key)
return x;
if(x->key > key)
return search(x->left, key);
return search(x->right, key);
}
return x;
}
(6)求树最大值、最小值(递归实现)
pnode tree_max(pnode x){
if(x != nil){
if(x->right != nil)
return tree_max(x->right);
return x;
}
return x;
}
pnode tree_min(pnode x){
if(x != nil){
if(x->left != nil)
return tree_min(x->left);
return x;
}
return x;
}
(7)某节点的successor节点、predecessor节点:
pnode successor(pnode x){
if(x->right != nil)
return tree_min(x->right);
else{
pnode par = x->p;
while(par != nil && x == par->right){ //画z字形
x = par; par = par->p;
}
return par;
}
}
pnode predecessor(pnode x){
if(x->left != nil)
return tree_max(x->left);
else{
pnode par = x->p;
while(par != nil && x == par->left){
x = par; par = par->p;
}
return par;
}
}
(8)删除某节点z,分3种情况讨论:
1、z没有children:直接删除; 2、z有2个children,用successor(z)代替z被删除,且z的值全部换成successor的值;
3、z只有一个child,将child移到z的位置即可。
void tree_delete(pnode &z){
if(z->left == nil && z->right == nil){ //z has no child
if(z == z->p->left)
z->p->left = nil;
else
z->p->right = nil;
}
else if(z->left != nil && z->right != nil){ //z have both 2 children
pnode next = successor(z);
z->key = next->key;
if(next == next->p->left)
next->p->left = nil;
else
next->p->right = nil;
}
else if(z->left != nil){ //z only has the left child
if(z == z->p->left)
z->p->left = z->left;
else
z->p->right = z->left;
z->left->p = z->p;
}
else{ //z only has the right child
if(z == z->p->left)
z->p->left = z->right;
else
z->p->right = z->right;
z->right->p = z->p;
}
}