Download presentation
Presentation is loading. Please wait.
1
Lecture No.20 Data Structures Dr. Sohail Aslam
2
AVL Tree AVL (Adelson-Velskii and Landis) tree.
An AVL tree is identical to a BST except height of the left and right subtrees can differ by at most 1. height of an empty tree is defined to be (–1). Start of 20 (Nov 29)
3
AVL Tree An AVL Tree height 5 2 8 1 1 4 7 2 3 3
4
AVL Tree Not an AVL tree height 6 1 8 1 1 4 2 3 5 3
5
Balanced Binary Tree The height of a binary tree is the maximum level of its leaves (also called the depth). The balance of a node in a binary tree is defined as the height of its left subtree minus height of its right subtree. Here, for example, is a balanced tree. Each node has an indicated balance of 1, 0, or –1.
6
Balanced Binary Tree -1 1 1 -1 End of 19
7
Insertions and effect on balance
Balanced Binary Tree Insertions and effect on balance -1 1 1 -1 B B U1 U2 U3 U4 B B B B U5 U6 U7 U8 U9 U10 U11 U12
8
Balanced Binary Tree Tree becomes unbalanced only if the newly inserted node is a left descendant of a node that previously had a balance of 1 (U1 to U8), or is a descendant of a node that previously had a balance of –1 (U9 to U12)
9
Insertions and effect on balance
Balanced Binary Tree Insertions and effect on balance -1 1 1 -1 B B U1 U2 U3 U4 B B B B U5 U6 U7 U8 U9 U10 U11 U12
10
Balanced Binary Tree Consider the case of node that was previously 1
-1 1 1 -1 B B U1 U2 U3 U4 B B B B U5 U6 U7 U8 U9 U10 U11 U12
11
Inserting New Node in AVL Tree
1 B T1 T2 T3 1
12
Inserting New Node in AVL Tree
2 B 1 T1 T2 T3 1 2 new
13
Inserting New Node in AVL Tree
2 B A B 1 T1 T1 T2 T3 T2 1 T3 2 new new Inorder: T1 B T2 A T3 Inorder: T1 B T2 A T3
14
AVL Tree Building Example
Let us work through an example that inserts numbers in a balanced search tree. We will check the balance after each insert and rebalance if necessary using rotations.
15
AVL Tree Building Example
Insert(1) 1
16
AVL Tree Building Example
Insert(2) 1 2
17
AVL Tree Building Example
Insert(3) single left rotation 1 -2 2 3
18
AVL Tree Building Example
Insert(3) single left rotation 1 -2 2 3
19
AVL Tree Building Example
Insert(3) 2 1 3 End of lecture 20
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.