Module 3-1
Module 3-1
Basics
Binary Search Tree
• Properties of Binary Search Tree:
• The left subtree of a node contains only nodes with keys
less than the node’s key.
• The right subtree of a node contains only nodes with keys
greater than the node’s key.
• The left and right subtree each must also be a binary
search tree.
• There must be no duplicate nodes(BST may have
duplicate values with different handling approaches).
insertion
AVL
• AVL Tree was designed by Adelson-Velski and Landis in
1962. Thus, AVL represents the first letter of each
originator’s first alphabet.
• AVL tree is a self-balancing binary search tree. It
balances the height of left subtree and right subtree.
• An AVL tree is called balanced when the difference of
height is -1, 0, 1. It is also called balance factor (BF).
• BALANCE FACTOR = Height of left subtree – Height
of right subtree
How to check the height
Every leaf has balance factor 0.
Beginning at 0 from the leaves, the count will increase to
the root.
• If the difference becomes more than 1 or less than -1,
then we have to perform rotation to balance the height of
subtrees.
• Insert 12
• AVL tree insert 12
• The 12 is less than 50 (12 < 50), So it will be the left child
of 50. 50, 12, 10, 72, 54, 95, 1, 52, 98
insert 10
AVL tree insert 10
The 10 is less than 12 (10 < 12), So it will be the left child of
12.
12 has balance factor 1.
50 has balance factor = 2 – 0 = 2.
By looking at the tree, we do right rotation.
As a result of rotation, 12 is the root. 10 is left child and 50
is right child of 12.
Input is – {50, 12, 10, 72, 54, 95, 1, 52, 98}
• Insert 72
• AVL tree insert 72
• 72 is greater than 50 (50 < 72), So it will be the right child
of 50.
• 50 has balance factor -1.
• 12 has balance factor -1.
• Insert 54 Input is – {50, 12, 10, 72, 54, 95, 1, 52, 98}
• AVL tree insert 54
• 54 is less than 72 (54 < 72), So it will
be the left child of 72.
• 72 has balance factor 1.
• 50 has balance factor -2.
• We can overcome this problem by
rotating node 50 to the left. However,
54 is already in the left position. Also,
if 54 becomes the child with 50, we’ll
have to go through another rotation.
As a result, 54 and 72 will rotate to the
right on the first rotation, whereas 50
will revolve to the left. We rotate
(Right-Left).
• As a result of rotations, 54 is the
parent of 50 and 72.
• Insert 95 Input is – {50, 12, 10, 72, 54, 95, 1, 52, 98}