Left rotate a BST

on Saturday, November 28, 2009


A node of binary search tree is given. Write a code which will left rotate the tree about given node.












SOLUTION

void left_rotate ( tree * x){
tree * y = x->right;
tree *z = x->parent;

x->right = y->left;
y->left->parent = x;
y->parent = z;

if ( z == NULL)
root = y;
else {
if ( x == z->left)
z->left = y;
else
z->right = y;
}
y->left = x;
x->parent = y;
}

4 comments:

Anonymous said...

v nid d prnt f d gvn nde 2 slv dis prblm.

hifun said...

@above:
then find it out. Well, u may assume that parent pointer is there in tree structure.

Anonymous said...

tree *z = x->parent;


so u r having three pointers in ur node(left, right, parent) rather than traditional two (left and right) pointer.....

hifun said...

@above:
yes, i've already mentioned it in 2nd post.
Even if it is not there, we can search it out ,but this will make left rotate linear in time.

Post a Comment