SlideShare a Scribd company logo
1
Balanced Tree
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
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:
20
9
2 15
5
10
30
7
1
1
1
1
2
3 2
4
10
4
data
height
left/
right
9
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
10
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
11
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
12
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;
}
13
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
14
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;
}

More Related Content

PPT
16-avl-trees for computer science and.ppt
PPTX
16-avl- balanced-123456789078-trees.pptx
PPTX
Lecture3
PPT
Avl tree
PDF
9 chapter4 trees_avl
PPT
DSA Leactrure # 2! Explaining abstract AVL trees
PPTX
Avl tress in data structures and algorithms
PPT
AVL-TREE.ppt
16-avl-trees for computer science and.ppt
16-avl- balanced-123456789078-trees.pptx
Lecture3
Avl tree
9 chapter4 trees_avl
DSA Leactrure # 2! Explaining abstract AVL trees
Avl tress in data structures and algorithms
AVL-TREE.ppt

Similar to 16-avl-trees.ppt data structures prestentation (20)

PPT
Presentation1 data structure for CSE.ppt
PDF
Avl tree detailed
PDF
data structure AVL TREES chapter slides for learning about AVL trees
PPTX
PPT
avl.ppt
PPT
avl.ppt
PPTX
Presentation_30219_Content_Document_20250107125144AM.pptx
PPTX
Avl trees final
PPT
PPT 2.5 AVL Trees is a ppt from trees topic dsa.ppt
PDF
Lect 13, 14 (final)AVL Tree and Rotations.pdf
PPTX
Avl trees
PDF
Lecture 10 - AVL Trees.pdf
PPTX
AVL Tree Data Structure
PPTX
AVL Tree of Data Structure presentation.pptx
PPTX
AVL tree PPT.pptx
PPT
AVL TREE PREPARED BY M V BRAHMANANDA REDDY
PPT
lec41.ppt
PPTX
mod 2.2 avl_red_black.pptx with good explanations
Presentation1 data structure for CSE.ppt
Avl tree detailed
data structure AVL TREES chapter slides for learning about AVL trees
avl.ppt
avl.ppt
Presentation_30219_Content_Document_20250107125144AM.pptx
Avl trees final
PPT 2.5 AVL Trees is a ppt from trees topic dsa.ppt
Lect 13, 14 (final)AVL Tree and Rotations.pdf
Avl trees
Lecture 10 - AVL Trees.pdf
AVL Tree Data Structure
AVL Tree of Data Structure presentation.pptx
AVL tree PPT.pptx
AVL TREE PREPARED BY M V BRAHMANANDA REDDY
lec41.ppt
mod 2.2 avl_red_black.pptx with good explanations
Ad

More from SyedAliShahid3 (14)

PPT
lecture3.pptlecture3 data structures pptt
PPT
SecurityPolicy.ppt SecurityPolicy.ppt
PPTX
webapplicationattacks-101005070110-phpapp02.pptx
PPT
144205230-Cross-Site-Scripting-XSS-ppt.ppt
PPT
linkedLists.ppt presentation on the topic
PPTX
Levels_of_Requirements_SRE.pptx presentation
PPTX
BST.pptx data structures presentation ppt
PPT
Unit24_TopologicalSort.ppt data structures
PPT
DivideAndConquer.pptDivideAndConquer.ppt
PPTX
AVLTrees.pptx data structures presentation
PPT
22-graphs1-dfs-bfs.ppt data structures ppt
PPT
25-graphs4-topological-sort.ppt data structures
PPT
dipfinal1--150927115011-lva1-app6891.ppt
PPT
QualityModelsAndAtttribQualityModels.ppt
lecture3.pptlecture3 data structures pptt
SecurityPolicy.ppt SecurityPolicy.ppt
webapplicationattacks-101005070110-phpapp02.pptx
144205230-Cross-Site-Scripting-XSS-ppt.ppt
linkedLists.ppt presentation on the topic
Levels_of_Requirements_SRE.pptx presentation
BST.pptx data structures presentation ppt
Unit24_TopologicalSort.ppt data structures
DivideAndConquer.pptDivideAndConquer.ppt
AVLTrees.pptx data structures presentation
22-graphs1-dfs-bfs.ppt data structures ppt
25-graphs4-topological-sort.ppt data structures
dipfinal1--150927115011-lva1-app6891.ppt
QualityModelsAndAtttribQualityModels.ppt
Ad

Recently uploaded (20)

PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Classroom Observation Tools for Teachers
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
Basic Mud Logging Guide for educational purpose
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
01-Introduction-to-Information-Management.pdf
PDF
RMMM.pdf make it easy to upload and study
PPTX
GDM (1) (1).pptx small presentation for students
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
Cell Structure & Organelles in detailed.
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PPTX
Pharma ospi slides which help in ospi learning
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Classroom Observation Tools for Teachers
Pharmacology of Heart Failure /Pharmacotherapy of CHF
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
Basic Mud Logging Guide for educational purpose
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPH.pptx obstetrics and gynecology in nursing
Renaissance Architecture: A Journey from Faith to Humanism
O5-L3 Freight Transport Ops (International) V1.pdf
01-Introduction-to-Information-Management.pdf
RMMM.pdf make it easy to upload and study
GDM (1) (1).pptx small presentation for students
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Microbial disease of the cardiovascular and lymphatic systems
Sports Quiz easy sports quiz sports quiz
Cell Structure & Organelles in detailed.
FourierSeries-QuestionsWithAnswers(Part-A).pdf
TR - Agricultural Crops Production NC III.pdf
Pharma ospi slides which help in ospi learning
school management -TNTEU- B.Ed., Semester II Unit 1.pptx

16-avl-trees.ppt data structures prestentation

  • 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 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: 20 9 2 15 5 10 30 7 1 1 1 1 2 3 2 4 10 4 data height left/ right
  • 9. 9 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
  • 10. 10 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
  • 11. 11 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
  • 12. 12 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; }
  • 13. 13 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
  • 14. 14 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; }