Open In App

Data Structures | Balanced Binary Search Trees | Question 7

Like Article
Like
Save Article
Save
Share
Report issue
Report

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




// A utility function to right rotate subtree rooted with y
// See the diagram given above.
struct node *rightRotate(struct node *y)
{
    struct node *x = y->left;
    struct node *T2 = x->right;
   
    // Perform rotation
    x->right = y;
    y->left = T2;
   
    // Update heights
    y->height = max(height(y->left), height(y->right))+1;
    x->height = max(height(x->left), height(x->right))+1;
   
    // Return new root
    return x;
}
   
// A utility function to left rotate subtree rooted with x
// See the diagram given above.
struct node *leftRotate(struct node *x)
{
    struct node *y = x->right;
    struct node *T2 = y->left;
   
    // Perform rotation
    y->left = x;
    x->right = T2;
   
    //  Update heights
    x->height = max(height(x->left), height(x->right))+1;
    y->height = max(height(y->left), height(y->right))+1;
   
    // Return new root
    return y;
}



Quiz of this Question


Last Updated : 28 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads