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

📅  最后修改于: 2021-09-08 14:54:14             🧑  作者: 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

以下哪项是左旋和右旋操作的最紧上限。

(一) O(1)
(B) O(登录)
(C) O(LogLogn)
(D) O(n)答案:(一)
说明:旋转操作(左右旋转)需要恒定的时间,因为那里只有很少的指针被改变。以下是左旋转和右旋转的 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;
}

这个问题的测验