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/