Binary Search Tree
regarding with the action : search , search_min , search_max ,
search_predecessor , search_successor.
Data structure of the tree
struct tree_node{
unsigned int data;
struct tree_node *left, *right, *parent;
};
struct tree_node x;
Key(x) : x->data
Parent(x) : x->parent
Left(x) : x->left
Right(x) : x->right
Inodertraverse : 1->2->3->4->5->6->7
if u inodertraverse the binary search trees, the result must be Ascending.
So , if node has two children(left and right),
the predecessor of that node must be the maximunm of node->left
likewisely ;
the successor of that node must be the minimum of node->right
1 search :
unsigned char *search(struct tree_node *x, int v)
{
if(Key(x) == v)
return x;
if(v > Key(x))
search(Right(x), v);
else if(v < Key(x))
search(Left(x), v);
}
2 search_min :
just look up recursively along with left pointer of every node until
encountering with NULL
unsigned char *search_min(struct tree_node *root)
{
struct tree_node *now = root;
while(now != NULL)
now = Left(now);
return now;
}
3 search_max
the same principle as the min , look up recursively along with the right pionter
of every node until encountering with NULL
unsigned char *search_max(struct tree_node *root)
{
struct tree_node *now = root;
while(now != NULL)
now = Right(now);
return now;
}
question of successor or predecessor
4 search_successor
spilted into 2 circumstances :
(1)when the node->right != NULL , just find the minimun item of the node-
>right , just like 4 is the successor of 3
(2)when node->right == NULL , just find the first ancesstor whose left
child is also the ancestor of that node , just like 5 ->6
unsigned char *search_successor(struct tree_node *x)
{
if(Right(x) != NULL)
return search_min(Right(x));
else{
y = Parent(x);
while(y != NULL && Right(y) == x){
x = y;
y = Parent(y);
}
return y;
}
}
5 search_predecessor
in comparsion to the successor one , can draw the conclusion that
(1)when node->left != NULL , just find the maximun iten of node->left
(2)if not , apply same priciple , like 3 is the predecessor of 4
unsigned char *search_predecessor(struct tree_node *x)
{
if(Left(x) != NULL)
return search_max(Left(x));
else{
y = Parent(x);
while(y != NULL && Left(y) == x){
x = y;
y = Parent(y);
}
}
}