Tree Balancing
Tree Balancing
AVL tree checks the height of left and right sub-trees and
assures that the difference is not more than 1.
4 cases:
Outside Cases (require single rotation) :
1. Insertion into left subtree of left child of .
2. Insertion into right subtree of right child of .
Inside Cases (require double rotation) :
3. Insertion into left subtree of right child of .
4. Insertion into right subtree of left child of .
Case 1: Insertion into left subtree of left child of
RIGHT ROTATION
AVL tree may become unbalanced if a node is inserted in the
left subtree of left subtree. The tree then needs a right
rotation.
Case 2: Insertion into right subtree of right child of
LEFT ROTATION
If a tree become unbalanced, when a node is inserted into the
right subtree of right subtree, then we perform single left
rotation.
Case 3:Insertion into left subtree of right child of
https://www.cs.usfca.edu/~galles/visualization/RedBlack.html
Comparison with AVL Tree
• The AVL trees are more balanced compared to Red
Black Trees, but they may cause more rotations
during insertion and deletion.
• So if your application involves many frequent
insertions and deletions, then Red Black trees should
be preferred.
• If the insertions and deletions are less frequent and
search is more frequent operation, then AVL tree
should be preferred over Red Black Tree.
MULTIWAY SEARCH TREES
• A multiway search tree is one with nodes that
have two or more children.
• Within each node is stored a given key, which
is associated to an item we wish to access
through the structure.
2-4 Trees
a. Nodes may contain 1, 2 or 3 items.
b. A node with k items has k + 1 children
c. All leaves are on same level.
Example
10 45
3 8 25 38 70 90 100
Insertion
insert 80
10 45
3 8 25 38 70 80 90 100
Overflow!
Insertion
Split & move middle element to parent
10 45 80
3 8 25 38 70 90 100
https://www.cs.usfca.edu/~galles/visualization/BTree.html
B-Trees
10 20 30 40 50 60 70
1 2 3 4 8 6 7 8 9 11 22 33 44 55 66 77