AVL tree

self balancing tree, named after their inventors, Adelson-Velskii and Landis.

- difference between heights of left node and right node should be less than or equal to one

- the height of balanced tree is log(n). If skewed, it's n.

- BST rule, keys(left) < keys(root) < keys(right)

- BST basic operations, left rotation and right rotation

- more operations compared to red-black tree when insert or delete. but more balanced than red-black tree. thus it's more suitable in the case with less insertion or deletion.

- impl note.

  1, standard BST insertion of node w

  2, travel up from w to find the first unbalanced node z. y is child node of z comes on the path from w to z. x is the grandchild of z comes on the path from w to z

  3, rebalance the tree by performing right and left rotations. There are four cases.

     A, left left case

          

T1, T2, T3 and T4 are subtrees.
         z                                      y 
        / \                                   /   \
       y   T4      Right Rotate (z)          x      z
      / \          - - - - - - - - ->      /  \    /  \ 
     x   T3                               T1  T2  T3  T4
    / \
  T1   T2

     B, left right case

     z                               z                           x
    / \                            /   \                        /  \ 
   y   T4  Left Rotate (y)        x    T4  Right Rotate(z)    y      z
  / \      - - - - - - - - ->    /  \      - - - - - - - ->  / \    / \
T1   x                          y    T3                    T1  T2 T3  T4
    / \                        / \
  T2   T3                    T1   T2

     C, right right case

  z                                y
 /  \                            /   \ 
T1   y     Left Rotate(z)       z      x
    /  \   - - - - - - - ->    / \    / \
   T2   x                     T1  T2 T3  T4
       / \
     T3  T4

     D, right left case

   z                            z                            x
  / \                          / \                          /  \ 
T1   y   Right Rotate (y)    T1   x      Left Rotate(z)   z      y
    / \  - - - - - - - - ->     /  \   - - - - - - - ->  / \    / \
   x   T4                      T2   y                  T1  T2  T3  T4
  / \                              /  \
T2   T3                           T3   T4

structure:

class Node{

int value;

Node left;

Node right;

int height;

}

Node parent;

parent.height = max-height(parent.left, parent.right)

isbalance = max.abs(parent.left.height - parent.right.height) > 1

 

references http://www.geeksforgeeks.org/avl-tree-set-1-insertion/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值