SlideShare a Scribd company logo
1
CSE 373
AVL trees
read: Weiss Ch. 4, section 4.1 - 4.4
slides created by Marty Stepp
http://www.cs.washington.edu/373/
© University of Washington, all rights reserved.
2
Trees and balance
• balanced tree: One whose subtrees differ in height by at most 1 and
are themselves balanced.
 A balanced tree of N nodes has a height of ~ log2 N.
 A very unbalanced tree can have a height close to N.
 The runtime of adding to / searching a
BST is closely related to height.
 Some tree collections (e.g. TreeSet)
contain code to balance themselves
as new nodes are added.
19
7
14
6
9
8
4
root
height = 4
(balanced)
3
Some height numbers
• Observation: The shallower the BST the better.
 Average case height is O(log N)
 Worst case height is O(N)
 Simple cases such as adding (1, 2, 3, ..., N), or the opposite order,
lead to the worst case scenario: height O(N).
• For binary tree of height h:
 max # of leaves: 2h-1
 max # of nodes: 2h
- 1
 min # of leaves:1
 min # of nodes:h
21
18
20
8
15
14
2
root
4
Calculating tree height
• Height is max number of nodes in path from root to any leaf.
 height(null) = 0
 height(a leaf) = ?
 height(A) = ?
 Hint: it's recursive!
 height(a leaf) = 1
 height(A) = 1 + max(
height(A.left), height(A.right))
A
A.left A.right
5
AVL trees
• AVL tree: a binary search tree that uses modified add and remove
operations to stay balanced as its elements change
 one of several kinds of auto-balancing trees (others in book)
 invented in 1962 by two Russian mathematicians
• (Adelson-Velskii and Landis)
• A-V & L proved that an AVL tree's height is always O(log N).
 basic idea: When nodes are added to / removed from the tree,
if the tree becomes unbalanced, repair the tree until balance is
restored.
• rebalancing operations are relatively efficient (O(1))
• overall tree maintains a balanced O(log N) height, fast to add/search
6
Balance factor
• balance factor, for a tree node T :
 = height of T's right subtree minus height of T's left subtree.
 BF(T) = Height(T.right) - Height(T.left)
• (the tree at right shows BF of each node)
 an AVL tree maintains a "balance factor"
in each node of 0, 1, or -1
• i.e. no node's two child subtrees
differ in height by more than 1
 it can be proven that the height of an
AVL tree with N nodes is O(log N)
-2
3 1
-1
-2
0
0
7
AVL tree examples
• Two binary search trees:
 (a) an AVL tree
 (b) not an AVL tree (unbalanced nodes are darkened)
8
Which are valid AVL trees?
• What is the balance factor of each tree node?
5
2 7
-1
-2 3
-4
9
4 20
0 15 22
11 33
14
9 28
6 31
44
8
3
1
4
2 5
3
4
9
Tracking subtree height
• Many of the AVL tree operations depend on height.
 Height can be computed recursively by walking the tree; too slow.
 Instead, each node can keep track of its subtree height as a field:
private class TreeNode {
private E data;
private int height;
private TreeNode left;
private TreeNode right;
}
20
9
2 15
5
10
30
7
1
1
1
1
2
3 2
4
10
4
data
height
left/
right
10
AVL add operation
• For all AVL operations, we assume the tree was balanced before the
operation began.
 Adding a new node begins the same as with a typical BST, traversing left
and right to find the proper location and attaching the new node.
 But adding this new node may unbalance the tree by 1:
set.add(49);
87
29
55
42
-3
49
11
AVL add cases
• Consider the lowest node k2 that has now become unbalanced.
 The new offending node could be in one of the four following
grandchild subtrees, relative to k2:
1) Left-Left, 2) Left-Right, 3) Right-Left, 4) Right-Right
12
Key idea: rotations
• If a node has become out of balanced in a given direction, rotate it
in the opposite direction.
 rotation: A swap between parent and left or right child,
maintaining proper BST ordering.
8
25
3
rotate right
8
25
3
11 11
13
Right rotation
• right rotation (clockwise): (fixes Case 1 (LL))
 left child k1 becomes parent
 original parent k2 demoted to right
 k1's original right subtree B (if any) is attached to k2 as left subtree
14
Right rotation example
• What is the balance factor of k2 before and after rotating?
15
Right rotation steps
1. Detach left child (11)'s right subtree (27) (don't lose it!)
2. Consider left child (11) be the new parent.
3. Attach old parent (43) onto right of new parent (11).
4. Attach new parent (11)'s old right subtree (27)
as left subtree of old parent (43).
11
43
8 27
65
3
11
43
8
27 65
3
11
43
8 27
65
3
16
Right rotation code
private TreeNode rightRotate(TreeNode oldParent) {
// 1. detach left child's right subtree
TreeNode orphan = oldParent.left.right;
// 2. consider left child to be the new parent
TreeNode newParent = oldParent.left;
// 3. attach old parent onto right of new parent
newParent.right = oldParent;
// 4. attach new parent's old right subtree as
// left subtree of old parent
oldParent.left = orphan;
oldParent.height = height(oldParent); // update nodes'
newParent.height = height(newParent); // height values
return newParent;
}
17
Right rotation code
private int height(TreeNode node) {
if (node == null) {
return 0;
}
int left = (node.left == null) ? 0 : node.left.height;
int right = (node.right == null) ? 0 : node.right.height;
return Math.max(left, right) + 1;
}
18
Left rotation
• left rotation (counter-clockwise): (fixes Case 4 (RR))
 right child k2 becomes parent
 original parent k1 demoted to left
 k2's original left subtree B (if any) is attached to k1 as left subtree
19
Left rotation steps
1. Detach right child (65)'s left subtree (51) (don't lose it!)
2. Consider right child (65) be the new parent.
3. Attach old parent (43) onto left of new parent (65).
4. Attach new parent (65)'s old left subtree (51)
as right subtree of old parent (43).
65
43
87
51
21
73
21
43
65
51 87
73
65
87
43
73
21 51
20
Left rotation code
private TreeNode leftRotate(TreeNode oldParent) {
// 1. detach right child's left subtree
TreeNode orphan = oldParent.right.left;
// 2. consider right child to be the new parent
TreeNode newParent = oldParent.right;
// 3. attach old parent onto left of new parent
newParent.left = oldParent;
// 4. attach new parent's old left subtree as
// right subtree of old parent
oldParent.right = orphan;
oldParent.height = height(oldParent); // update nodes'
newParent.height = height(newParent); // height values
return newParent;
}
21
Problem cases
• A single right rotation does not fix Case 2 (LR).
 (Similarly, a single left rotation does not fix Case 3 (RL).)
22
Left-right double rotation
• left-right double rotation: (fixes Case 2 (LR))
 1) left-rotate k3's left child ... reduces Case 2 into Case 1
 2) right-rotate k3 to fix Case 1
23
Left-right rotation example
• What is the balance factor of k1, k2, k3 before and after rotating?
24
Right-left double rotation
• right-left double rotation: (fixes Case 3 (RL))
 1) right-rotate k1's right child ... reduces Case 3 into Case 4
 2) left-rotate k1 to fix Case 4
25
AVL add example
• Draw the AVL tree that would result if the following numbers were
added in this order to an initially empty tree:
 20, 45, 90, 70, 10, 40, 35, 30, 99, 60, 50, 80
99
80
90
60
70
50
20
45
10
40
30
35

More Related Content

PPT
16-avl-trees.ppt data structures prestentation
SyedAliShahid3
 
PDF
Sienna6bst 120411102353-phpapp02
Getachew Ganfur
 
PDF
Lecture 10 - AVL Trees.pdf
SanghdipUdrake
 
PDF
Avl trees
Xad Kuain
 
PPT
Avl tree
Van Pham
 
PPT
AVL TREE PREPARED BY M V BRAHMANANDA REDDY
Malikireddy Bramhananda Reddy
 
PPT
Tree
Ghaffar Khan
 
16-avl-trees.ppt data structures prestentation
SyedAliShahid3
 
Sienna6bst 120411102353-phpapp02
Getachew Ganfur
 
Lecture 10 - AVL Trees.pdf
SanghdipUdrake
 
Avl trees
Xad Kuain
 
Avl tree
Van Pham
 
AVL TREE PREPARED BY M V BRAHMANANDA REDDY
Malikireddy Bramhananda Reddy
 

Similar to 16-avl- balanced-123456789078-trees.pptx (20)

PPTX
Adelson velskii Landis rotations based on
banupriyar5
 
PPT
avl.ppt
plagcheck
 
PPT
avl.ppt
cotisa2402
 
PPTX
Data structures trees and graphs - AVL tree.pptx
MalligaarjunanN
 
PPTX
Avl tree ppt
Surkhab Shelly
 
PDF
data structure AVL TREES chapter slides for learning about AVL trees
ethar2303338
 
PPTX
Tree traversal techniques
Syed Zaid Irshad
 
PPTX
AVL Tree.pptx
Trad5
 
PPT
BINARY TREE REPRESENTATION.ppt
SeethaDinesh
 
PPT
AVL_Trees.ppt
SaqibShigri
 
PPT
lecture18(1) for the data structure .ppt
umakalaimani1
 
PPT
Presentation1 data structure for CSE.ppt
umakalaimani1
 
PDF
9 chapter4 trees_avl
SSE_AndyLi
 
PPTX
Avl trees final
PRAKASH RANJAN SINGH
 
PPT
bst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
shesnasuneer
 
PPT
Leftist heap
Shuvro Roy
 
PPT
Av ltrees
Jeet Poria
 
PPT
Binary Search Tree
AdityaK92
 
Adelson velskii Landis rotations based on
banupriyar5
 
avl.ppt
plagcheck
 
avl.ppt
cotisa2402
 
Data structures trees and graphs - AVL tree.pptx
MalligaarjunanN
 
Avl tree ppt
Surkhab Shelly
 
data structure AVL TREES chapter slides for learning about AVL trees
ethar2303338
 
Tree traversal techniques
Syed Zaid Irshad
 
AVL Tree.pptx
Trad5
 
BINARY TREE REPRESENTATION.ppt
SeethaDinesh
 
AVL_Trees.ppt
SaqibShigri
 
lecture18(1) for the data structure .ppt
umakalaimani1
 
Presentation1 data structure for CSE.ppt
umakalaimani1
 
9 chapter4 trees_avl
SSE_AndyLi
 
Avl trees final
PRAKASH RANJAN SINGH
 
bst-class-220902051152-cdddddddddddddddddd5e6c70f.ppt
shesnasuneer
 
Leftist heap
Shuvro Roy
 
Av ltrees
Jeet Poria
 
Binary Search Tree
AdityaK92
 
Ad

Recently uploaded (20)

PPTX
AgentX UiPath Community Webinar series - Delhi
RohitRadhakrishnan8
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
PDF
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
PDF
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
PPTX
Inventory management chapter in automation and robotics.
atisht0104
 
PDF
Zero carbon Building Design Guidelines V4
BassemOsman1
 
PPTX
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
PDF
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
PDF
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
PDF
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
The Asian School
 
PDF
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
PDF
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
PPTX
22PCOAM21 Session 2 Understanding Data Source.pptx
Guru Nanak Technical Institutions
 
PDF
Introduction to Data Science: data science process
ShivarkarSandip
 
PPTX
Introduction of deep learning in cse.pptx
fizarcse
 
PDF
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
PPTX
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
PPTX
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
DOCX
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
PDF
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
AgentX UiPath Community Webinar series - Delhi
RohitRadhakrishnan8
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
flutter Launcher Icons, Splash Screens & Fonts
Ahmed Mohamed
 
20ME702-Mechatronics-UNIT-1,UNIT-2,UNIT-3,UNIT-4,UNIT-5, 2025-2026
Mohanumar S
 
Inventory management chapter in automation and robotics.
atisht0104
 
Zero carbon Building Design Guidelines V4
BassemOsman1
 
database slide on modern techniques for optimizing database queries.pptx
aky52024
 
Advanced LangChain & RAG: Building a Financial AI Assistant with Real-Time Data
Soufiane Sejjari
 
settlement FOR FOUNDATION ENGINEERS.pdf
Endalkazene
 
Traditional Exams vs Continuous Assessment in Boarding Schools.pdf
The Asian School
 
EVS+PRESENTATIONS EVS+PRESENTATIONS like
saiyedaqib429
 
Cryptography and Information :Security Fundamentals
Dr. Madhuri Jawale
 
22PCOAM21 Session 2 Understanding Data Source.pptx
Guru Nanak Technical Institutions
 
Introduction to Data Science: data science process
ShivarkarSandip
 
Introduction of deep learning in cse.pptx
fizarcse
 
Chad Ayach - A Versatile Aerospace Professional
Chad Ayach
 
MT Chapter 1.pptx- Magnetic particle testing
ABCAnyBodyCanRelax
 
Chapter_Seven_Construction_Reliability_Elective_III_Msc CM
SubashKumarBhattarai
 
SAR - EEEfdfdsdasdsdasdasdasdasdasdasdasda.docx
Kanimozhi676285
 
67243-Cooling and Heating & Calculation.pdf
DHAKA POLYTECHNIC
 
Ad

16-avl- balanced-123456789078-trees.pptx

  • 1. 1 CSE 373 AVL trees read: Weiss Ch. 4, section 4.1 - 4.4 slides created by Marty Stepp http://www.cs.washington.edu/373/ © University of Washington, all rights reserved.
  • 2. 2 Trees and balance • balanced tree: One whose subtrees differ in height by at most 1 and are themselves balanced.  A balanced tree of N nodes has a height of ~ log2 N.  A very unbalanced tree can have a height close to N.  The runtime of adding to / searching a BST is closely related to height.  Some tree collections (e.g. TreeSet) contain code to balance themselves as new nodes are added. 19 7 14 6 9 8 4 root height = 4 (balanced)
  • 3. 3 Some height numbers • Observation: The shallower the BST the better.  Average case height is O(log N)  Worst case height is O(N)  Simple cases such as adding (1, 2, 3, ..., N), or the opposite order, lead to the worst case scenario: height O(N). • For binary tree of height h:  max # of leaves: 2h-1  max # of nodes: 2h - 1  min # of leaves:1  min # of nodes:h 21 18 20 8 15 14 2 root
  • 4. 4 Calculating tree height • Height is max number of nodes in path from root to any leaf.  height(null) = 0  height(a leaf) = ?  height(A) = ?  Hint: it's recursive!  height(a leaf) = 1  height(A) = 1 + max( height(A.left), height(A.right)) A A.left A.right
  • 5. 5 AVL trees • AVL tree: a binary search tree that uses modified add and remove operations to stay balanced as its elements change  one of several kinds of auto-balancing trees (others in book)  invented in 1962 by two Russian mathematicians • (Adelson-Velskii and Landis) • A-V & L proved that an AVL tree's height is always O(log N).  basic idea: When nodes are added to / removed from the tree, if the tree becomes unbalanced, repair the tree until balance is restored. • rebalancing operations are relatively efficient (O(1)) • overall tree maintains a balanced O(log N) height, fast to add/search
  • 6. 6 Balance factor • balance factor, for a tree node T :  = height of T's right subtree minus height of T's left subtree.  BF(T) = Height(T.right) - Height(T.left) • (the tree at right shows BF of each node)  an AVL tree maintains a "balance factor" in each node of 0, 1, or -1 • i.e. no node's two child subtrees differ in height by more than 1  it can be proven that the height of an AVL tree with N nodes is O(log N) -2 3 1 -1 -2 0 0
  • 7. 7 AVL tree examples • Two binary search trees:  (a) an AVL tree  (b) not an AVL tree (unbalanced nodes are darkened)
  • 8. 8 Which are valid AVL trees? • What is the balance factor of each tree node? 5 2 7 -1 -2 3 -4 9 4 20 0 15 22 11 33 14 9 28 6 31 44 8 3 1 4 2 5 3 4
  • 9. 9 Tracking subtree height • Many of the AVL tree operations depend on height.  Height can be computed recursively by walking the tree; too slow.  Instead, each node can keep track of its subtree height as a field: private class TreeNode { private E data; private int height; private TreeNode left; private TreeNode right; } 20 9 2 15 5 10 30 7 1 1 1 1 2 3 2 4 10 4 data height left/ right
  • 10. 10 AVL add operation • For all AVL operations, we assume the tree was balanced before the operation began.  Adding a new node begins the same as with a typical BST, traversing left and right to find the proper location and attaching the new node.  But adding this new node may unbalance the tree by 1: set.add(49); 87 29 55 42 -3 49
  • 11. 11 AVL add cases • Consider the lowest node k2 that has now become unbalanced.  The new offending node could be in one of the four following grandchild subtrees, relative to k2: 1) Left-Left, 2) Left-Right, 3) Right-Left, 4) Right-Right
  • 12. 12 Key idea: rotations • If a node has become out of balanced in a given direction, rotate it in the opposite direction.  rotation: A swap between parent and left or right child, maintaining proper BST ordering. 8 25 3 rotate right 8 25 3 11 11
  • 13. 13 Right rotation • right rotation (clockwise): (fixes Case 1 (LL))  left child k1 becomes parent  original parent k2 demoted to right  k1's original right subtree B (if any) is attached to k2 as left subtree
  • 14. 14 Right rotation example • What is the balance factor of k2 before and after rotating?
  • 15. 15 Right rotation steps 1. Detach left child (11)'s right subtree (27) (don't lose it!) 2. Consider left child (11) be the new parent. 3. Attach old parent (43) onto right of new parent (11). 4. Attach new parent (11)'s old right subtree (27) as left subtree of old parent (43). 11 43 8 27 65 3 11 43 8 27 65 3 11 43 8 27 65 3
  • 16. 16 Right rotation code private TreeNode rightRotate(TreeNode oldParent) { // 1. detach left child's right subtree TreeNode orphan = oldParent.left.right; // 2. consider left child to be the new parent TreeNode newParent = oldParent.left; // 3. attach old parent onto right of new parent newParent.right = oldParent; // 4. attach new parent's old right subtree as // left subtree of old parent oldParent.left = orphan; oldParent.height = height(oldParent); // update nodes' newParent.height = height(newParent); // height values return newParent; }
  • 17. 17 Right rotation code private int height(TreeNode node) { if (node == null) { return 0; } int left = (node.left == null) ? 0 : node.left.height; int right = (node.right == null) ? 0 : node.right.height; return Math.max(left, right) + 1; }
  • 18. 18 Left rotation • left rotation (counter-clockwise): (fixes Case 4 (RR))  right child k2 becomes parent  original parent k1 demoted to left  k2's original left subtree B (if any) is attached to k1 as left subtree
  • 19. 19 Left rotation steps 1. Detach right child (65)'s left subtree (51) (don't lose it!) 2. Consider right child (65) be the new parent. 3. Attach old parent (43) onto left of new parent (65). 4. Attach new parent (65)'s old left subtree (51) as right subtree of old parent (43). 65 43 87 51 21 73 21 43 65 51 87 73 65 87 43 73 21 51
  • 20. 20 Left rotation code private TreeNode leftRotate(TreeNode oldParent) { // 1. detach right child's left subtree TreeNode orphan = oldParent.right.left; // 2. consider right child to be the new parent TreeNode newParent = oldParent.right; // 3. attach old parent onto left of new parent newParent.left = oldParent; // 4. attach new parent's old left subtree as // right subtree of old parent oldParent.right = orphan; oldParent.height = height(oldParent); // update nodes' newParent.height = height(newParent); // height values return newParent; }
  • 21. 21 Problem cases • A single right rotation does not fix Case 2 (LR).  (Similarly, a single left rotation does not fix Case 3 (RL).)
  • 22. 22 Left-right double rotation • left-right double rotation: (fixes Case 2 (LR))  1) left-rotate k3's left child ... reduces Case 2 into Case 1  2) right-rotate k3 to fix Case 1
  • 23. 23 Left-right rotation example • What is the balance factor of k1, k2, k3 before and after rotating?
  • 24. 24 Right-left double rotation • right-left double rotation: (fixes Case 3 (RL))  1) right-rotate k1's right child ... reduces Case 3 into Case 4  2) left-rotate k1 to fix Case 4
  • 25. 25 AVL add example • Draw the AVL tree that would result if the following numbers were added in this order to an initially empty tree:  20, 45, 90, 70, 10, 40, 35, 30, 99, 60, 50, 80 99 80 90 60 70 50 20 45 10 40 30 35