Data Structures | Balanced Binary Search Trees | Question 7
Consider the following left-rotate and right-rotate functions commonly used in self-adjusting BSTs
T1, T2 and T3 are subtrees of the tree rooted with y (on left side)
or x (on right side)
y x
/ \ Right Rotation / \
x T3 – - – - – - – > T1 y
/ \ < - - - - - - - / \
T1 T2 Left Rotation T2 T3
Which of the following is tightest upper bound for left-rotate and right-rotate operations.
(A) O(1)
(B) O(Logn)
(C) O(LogLogn)
(D) O(n)
Answer: (A)
Explanation: The rotation operations (left and right rotate) take constant time as only few pointers are being changed there. Following are C implementations of left-rotate and right-rotate
struct node *rightRotate( struct node *y)
{
struct node *x = y->left;
struct node *T2 = x->right;
x->right = y;
y->left = T2;
y->height = max(height(y->left), height(y->right))+1;
x->height = max(height(x->left), height(x->right))+1;
return x;
}
struct node *leftRotate( struct node *x)
{
struct node *y = x->right;
struct node *T2 = y->left;
y->left = x;
x->right = T2;
x->height = max(height(x->left), height(x->right))+1;
y->height = max(height(y->left), height(y->right))+1;
return y;
}
|
Quiz of this Question
Last Updated :
28 Jun, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...