Balanced+Trees REVIEW
Balanced+Trees REVIEW
REVIEW
The way a BST looks and performs depends on order of insertion of nodes:
Order 1: Order 2:
insert 4 insert 1
insert 2 insert 2
insert 6 insert 3
insert 1 insert 4
insert 3 insert 5
insert 5 insert 6
-1 -1
1
0 0 0 0
0 0 ALL ROTATIONS ARE
Left Rotate 0
Right Rotate Left Rotate O(1)
Left-Left case
0 Left Right case
0
2 2 2
1 -1 1
0 0 0 0
0 0 0
Right Rotate
Left Rotate Right Rotate
Insert (8) Insert (6) Insert (4) Stop here! There is an
imbalance, and we need
to rotate…
Right rotate
AVL TREE OPERATIONS
Insert/Delete – logic is same as for BST except Insert (10) Insert (9) Stop!
the AVL tree self-balances after every Right
left
insertion/deletion rotate
at 8
Notice: When inserting in an AVL tree,
we still must insert values LESS than node
to the LEFT of node, and values
GREATER than node to the RIGHT of
node, because valid AVL trees follow
BST properties (AVL trees are BSTs)
Continue…
Search – logic is same as for BST
2 + 6 + 27 = 35 unique keys