Documente Academic
Documente Profesional
Documente Cultură
by
P.VASUKI
Aug 2017
Need for balanced tree
• Try inserting the elements
100,98,45,38,31,26,22,11,8,1.
• You will land up with degenerative tree ..
Tree with every parent node with single
child.
• The worst case searching time is O(n)
• Why did you get so?. How do you wanted
to have a search tree to be smarter( with
less search time)
Need for a balanced tree
• Which do you prefer? What is the search
time complexity of both trees
A
A
B
B C
C
D F E
D
F
AVL (Adelson-Velskii and
Landis) tree
• A balanced binary search tree where
the height of the two subtrees
(children) of a node differs by at most
one.
• Look-up, insertion, and deletion are
O(log n), where n is the number of
nodes in the tree.
Height of a tree
• Height: the length of the longest
path from a node to a leaf.
height(leaf) = 0
height(an_empty_tree) = –1
Balancing the tree
• After every insertion and deletion
check the balance
1 so-called 1
‘dog-leg’
C C
B A
A B
There are no other possibilities for the left (or right) subtree
Localising the problem
Two principles:
• A is one level
higher 1
• Do single rotation
• Therefore make 1 C
the new root, 2 B
its right child and A
• Therefore make 1
the new root, 2 its
right child and B and
C the subtrees of 2 A B C
• Result: a more
balanced and legal
AVL tree
Single rotation
Picture Courtesy: Mark Allen Weiss Book
2 1
2
1
C
A B C
B
A
Left(right) imbalance (1)
[and right(left) imbalance by symmetry]
• Can’t use same
technique Picture Courtesy: Mark Allen Weiss Book
• Neither 1 nor 3
worked as root 2
node so make 2
1 3
the root
• Rearrange the
subtrees in the
correct order A B1 B2 C
• No matter how
deep B1 or B2
(+/- 0.5 levels)
we get a legal
double rotation
3 2
1 3
1
C
A B1 B2 C
A
B1 B2
private AvlNode<Anytype> insert(Anytype x, AvlNode<Anytype> t )
{
/*1*/ if( t == null )
t = new AvlNode<Anytype>( x, null, null );
/*2*/ else if( x.compareTo( t.element ) < 0 )
insert
{
t.left = insert( x, t.left ); method
if( height( t.left ) - height( t.right ) == 2 )
if( x.compareTo( t.left.element ) < 0 )
t = rotateWithLeftChild( t );
else
t = doubleWithLeftChild( t );
}
/*3*/ else if( x.compareTo( t.element ) > 0 )
{
t.right = insert( x, t.right );
if( height( t.right ) - height( t.left ) == 2 )
if( x.compareTo( t.right.element ) > 0 )
t = rotateWithRightChild( t );
else
t = doubleWithRightChild( t );
}
/*4*/ else
; // Duplicate; do nothing
t.height = max( height( t.left ), height( t.right ) ) + 1;
return t;
} Algorithm Courtesy: Mark Allen Weiss Book
rotateWithLeftChild method
private static AvlNode<Anytype> rotateWithLeftChild(
AvlNode<Anytype> k2 )
{
AvlNode<Anytype> k1 = k2.left;
k2.left = k1.right;
k1.right = k2;
k2.height = max( height( k2.left ), height( k2.right ) )
+ 1;
k1.height = max( height( k1.left ), k2.height ) + 1;
return k1;
}