• AVL tree rotate


    AVL tree
    ----------------------------------------------------------------------------
    rotate
    /**
     * Rotate binary tree node with left child.
     * For AVL trees, this is a single rotation for case 1.
     * Update heights, then set new root.
     */
    void rotateWithLeftChild( AvlNode * & k2 )
    {
        AvlNode *k1 = k2->left;
        k2->left = k1->right;
        k1->right = k2;
        k2->height = max( height( k2->left ), height( k2->right ) ) + 1;
        k1->height = max( height( k1->left ), k2->height ) + 1;
        k2 = k1;
    }
        
        k2
       / \
      k1  z
     / \
    x   y
    |
    -->
      k1
     / \
    x   k2
    |  / \
      y   z

    ----------------------------------------------------------------------------
    /**
     * Rotate binary tree node with right child.
     * For AVL trees, this is a single rotation for case 4.
     * Update heights, then set new root.
     */
    void rotateWithRightChild( AvlNode * & k1 )
    {
        AvlNode *k2 = k1->right;
        k1->right = k2->left;
        k2->left = k1;
        k1->height = max( height( k1->left ), height( k1->right ) ) + 1;
        k2->height = max( height( k2->right ), k1->height ) + 1;
        k1 = k2;
    }

       k1
      / \
     X   k2
         / \
         y  z
            |
    -->
       k2
      /  \
      k1  z
     / \  |
    x   y

    ----------------------------------------------------------------------------
    /**
     * Double rotate binary tree node: first left child.
     * with its right child; then node k3 with new left child.
     * For AVL trees, this is a double rotation for case 2.
     * Update heights, then set new root.
     */
    void doubleWithLeftChild( AvlNode * & k3 )
    {
        rotateWithRightChild( k3->left );
        rotateWithLeftChild( k3 );
    }    
    2
        k3
       / \
      k1  d
     / \        
    a   k2  
       / \
      b   c
    -->
        k2
       /  \
      k1   k3
     / \   / \    
    a  b   c  d
    ----------------------------------------------------------------------------
    /**
     * Double rotate binary tree node: first right child.
     * with its left child; then node k1 with new right child.
     * For AVL trees, this is a double rotation for case 3.
     * Update heights, then set new root.
     */
    void doubleWithRightChild( AvlNode * & k1 )
    {
        rotateWithLeftChild( k1->right );
        rotateWithRightChild( k1 );
    }

    3
      k1
     / \
    a   k3
       / \    
      k2  d
     / \
    b   c
    -->
        k2
       /  \
      k1   k3
     / \   / \    
    a  b   c  d
  • 相关阅读:
    centos7上搭建FTP(简单版)教程
    IDEA 添加外部jar包
    linux下搭建本地yum源
    Linux下 正则表达式的用法
    linux下rename用法--批量重命名
    Homebrew 常用命令
    纯内网环境下搭建zabbix
    windows下 批量修改文件名
    【转】git 的常用命令
    [转]linux 下 正则表达式的用法
  • 原文地址:https://www.cnblogs.com/BruceWayne09/p/16427700.html
Copyright © 2020-2023  润新知