Sunday, May 3, 2020

AVL TREE


AVL Tree is a tree where each of the root node does not have an imbalance between height of right and left sub tree

  • Minimal difference of 1 between height of left and right sub tree for each node.
    • THE FORMULA |Hr-Hl| <=1
  • Height of a tree is the length from longest leave to it's root.
  • For each node always count for imbalances after adding a new node.
  • The edge of the leave starts from 0
  • Visual Representation


How do you make a imbalanced tree into a AVL Tree

  1.  Use 4 type of rotation to fix their position
    1. LL ROTATION
    2. LR ROTATION

  1. RR ROTATION
  2. RL ROTATION
  1. THE rotation should be applied to only 3 nodes no matter how big the tree.
  2. The rotation should be done after every adding a new node and finding a height imbalance.
  3. How to Pick The Right node to rotate?
    1. Find the newly inserted node
    2. Go up through that node parents
    3. The first parents you find that's imbalance becomes "THE" node
  4. After you find "THE" node trace the step from that node to the newly added node
  5. Only take the first 2 step out of it to rotate for ex: RLLR only take RL
  6. Rotate the 3 node that has been trace according to the shape (RR, RL, LL, LR)
  7. Reconnect all the nodes that have been move
  8. If there exist a sub-node that collides with another sub node due to the position changed then insert it again using the BST rule.