📜  数据结构|平衡二叉搜索树|问题7

📅  最后修改于: 2021-06-29 00:57:00             🧑  作者: Mango

考虑以下自调整BST中常用的以下向左旋转和向右旋转功能

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

以下哪一项是向左旋转和向右旋转操作的最严格上限。

(A) O(1)
(B) O(登录)
(C) O(登录)
(D) O(n)答案: (A)
说明:旋转操作(向左和向右旋转)需要恒定的时间,因为在那里仅更改了几个指针。以下是向左旋转和向右旋转的C实现

// 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;
}

这个问题的测验