SlideShare una empresa de Scribd logo
1 de 36
AVL Trees

CENG 213 Data Structures

1
AVL Trees
•
•
•
•

An AVL tree is a binary search tree with a balance condition.
AVL is named for its inventors: Adel’son-Vel’skii and Landis
AVL tree approximates the ideal tree (completely balanced tree).
AVL Tree maintains a height close to the minimum.

Definition:
An AVL tree is a binary search tree such that
for any node in the tree, the height of the left and
right subtrees can differ by at most 1.

CENG 213 Data Structures

2
Figure 19.21
Two binary search trees: (a) an AVL tree; (b) not an AVL tree (unbalanced nodes are
darkened)

CENG 213 Data Structures

3
Figure 19.22
Minimum tree of height H

CENG 213 Data Structures

4
Properties
• The depth of a typical node in an AVL tree is very
close to the optimal log N.
• Consequently, all searching operations in an AVL
tree have logarithmic worst-case bounds.
• An update (insert or remove) in an AVL tree could
destroy the balance. It must then be rebalanced
before the operation can be considered complete.
• After an insertion, only nodes that are on the path
from the insertion point to the root can have their
balances altered.
CENG 213 Data Structures

5
Rebalancing
•

Suppose the node to be rebalanced is X. There are
4 cases that we might have to fix (two are the
mirror images of the other two):
1.
2.
3.
4.

•

An insertion in the left subtree of the left child of X,
An insertion in the right subtree of the left child of X,
An insertion in the left subtree of the right child of X, or
An insertion in the right subtree of the right child of X.

Balance is restored by tree rotations.

CENG 213 Data Structures

6
Balancing Operations: Rotations
• Case 1 and case 4 are symmetric and
requires the same operation for balance.
– Cases 1,4 are handled by single rotation.

• Case 2 and case 3 are symmetric and
requires the same operation for balance.
– Cases 2,3 are handled by double rotation.

CENG 213 Data Structures

7
Single Rotation
• A single rotation switches the roles of the parent
and child while maintaining the search order.
• Single rotation handles the outside cases (i.e. 1
and 4).
• We rotate between a node and its child.
– Child becomes parent. Parent becomes right child in
case 1, left child in case 4.

• The result is a binary search tree that satisfies the
AVL property.
CENG 213 Data Structures

8
Figure 19.23
Single rotation to fix case 1: Rotate right

CENG 213 Data Structures

9
Figure 19.26
Symmetric single rotation to fix case 4 : Rotate left

CENG 213 Data Structures

10
Figure 19.25
Single rotation fixes an AVL tree after insertion of 1.

CENG 213 Data Structures

11
Example
• Start with an empty AVL tree and insert the
items 3,2,1, and then 4 through 7 in
sequential order.
• Answer:
4

2

1

6

3

5

CENG 213 Data Structures

7

12
Analysis
• One rotation suffices to fix cases 1 and 4.
• Single rotation preserves the original height:
– The new height of the entire subtree is exactly the same
as the height of the original subtree before the insertion.

• Therefore it is enough to do rotation only at the
first node, where imbalance exists, on the path
from inserted node to root.
• Thus the rotation takes O(1) time.
• Hence insertion is O(logN)
CENG 213 Data Structures

13
Double Rotation
• Single rotation does not fix the inside cases
(2 and 3).
• These cases require a double rotation,
involving three nodes and four subtrees.

CENG 213 Data Structures

14
Figure 19.28
Single rotation does not fix case 2.

CENG 213 Data Structures

15
Left–right double rotation to fix case 2
Lift this up:
first rotate left between (k1,k2),
then rotate right betwen (k3,k2)

CENG 213 Data Structures

16
Left-Right Double Rotation
• A left-right double rotation is equivalent to
a sequence of two single rotations:
– 1st rotation on the original tree:
a left rotation between X’s left-child and
grandchild
– 2nd rotation on the new tree:
a right rotation between X and its new left
child.

CENG 213 Data Structures

17
Figure 19.30
Double rotation fixes AVL tree after the insertion of 5.

CENG 213 Data Structures

18
Right–Left double rotation to fix case 3.

CENG 213 Data Structures

19
Example
• Insert 16, 15, 14, 13, 12, 11, 10, and 8, and 9 to
the previous tree obtained in the previous single
rotation example.
• Answer:
7
13

4
6

2

1

3

11
9

5
8

15
12

14

16

10

CENG 213 Data Structures

20
Node declaration for AVL trees
template <class Comparable>
class AvlTree;
template <class Comparable>
class AvlNode
{
Comparable element;
AvlNode
*left;
AvlNode
*right;
int
height;
AvlNode( const Comparable & theElement, AvlNode *lt,
AvlNode *rt, int h = 0 )
: element( theElement ), left( lt ), right( rt ),
height( h ) { }
friend class AvlTree<Comparable>;
};
CENG 213 Data Structures

21
Height
template class <Comparable>
int
AvlTree<Comparable>::height( AvlNode<Comparable
> *t) const
{
return t == NULL ? -1 : t->height;
}

CENG 213 Data Structures

22
Single right rotation
/**
* Rotate binary tree node with left child.
* For AVL trees, this is a single rotation for case 1.
* Update heights, then set new root.
*/
template <class Comparable>
void
AvlTree<Comparable>::rotateWithLeftChild( AvlNode<Comparable>
* & k2 ) const
{
AvlNode<Comparable> *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;
k2 = k1;
}
CENG 213 Data Structures

23
Double Rotation
/**
* Double rotate binary tree node: first left child.
* with its right child; then node k3 with new left child.
* For AVL trees, this is a double rotation for case 2.
* Update heights, then set new root.
*/
template <class Comparable>
void
AvlTree<Comparable>::doubleWithLeftChild( AvlNode<Compa
rable> * & k3 ) const
{
rotateWithRightChild( k3->left );
rotateWithLeftChild( k3 );
}
CENG 213 Data Structures

24
/* Internal method to insert into a subtree.
* x is the item to insert.
* t is the node that roots the tree.
*/
template <class Comparable>
void AvlTree<Comparable>::insert( const Comparable & x, AvlNode<Comparable> * & t
) const
{
if( t == NULL )
t = new AvlNode<Comparable>( x, NULL, NULL );
else if( x < t->element )
{
insert( x, t->left );
if( height( t->left ) - height( t->right ) == 2 )
if( x < t->left->element )
rotateWithLeftChild( t );
else
doubleWithLeftChild( t );
}
else if( t->element < x )
{
insert( x, t->right );
if( height( t->right ) - height( t->left ) == 2 )
if( t->right->element < x )
rotateWithRightChild( t );
else
doubleWithRightChild( t );
}
else
; // Duplicate; do nothing
t->height = max( height( t->left ), height( t->right ) ) + 1;
}
CENG 213 Data Structures

25
AVL Tree -- Deletion
• Deletion is more complicated.
• We may need more than one rebalance on
the path from deleted node to root.
• Deletion is O(logN)

CENG 213 Data Structures

26
Deletion of a Node
• Deletion of a node x from an AVL tree
requires the same basic ideas, including
single and double rotations, that are used
for insertion.
• With each node of the AVL tree is
associated a balance factor that is left high,
equal or right high according, respectively,
as the left subtree has height greater than,
equal to, or less than that of the right
subtree.
CENG 213 Data Structures

27
Method
1. Reduce the problem to the case when the node x to
be deleted has at most one child.
–

–

If x has two children replace it with its immediate
predecessor y under inorder traversal (the immediate
successor would be just as good)
Delete y from its original position, by proceeding as
follows, using y in place of x in each of the following
steps.

CENG 213 Data Structures

28
Method (cont.)
2.

Delete the node x from the tree.
– We’ll trace the effects of this change on height through all
the nodes on the path from x back to the root.
– We use a Boolean variable shorter to show if the height
of a subtree has been shortened.
– The action to be taken at each node depends on
•
•
•

3.

the value of shorter
balance factor of the node
sometimes the balance factor of a child of the node.

shorter is initially true. The following steps are to be done
for each node p on the path from the parent of x to the root,
provided shorter remains true. When shorter becomes false,
the algorithm terminates.
CENG 213 Data Structures

29
Case 1
4.

Case 1: The current node p has balance factor equal.
– Change the balance factor of p.
– shorter becomes false
−

T1

p

T2



T1

p

• No rotations
• Height unchanged

T2

deleted

CENG 213 Data Structures

30
Case 2
5.

Case 2: The balance factor of p is not equal and the taller
subtree was shortened.
– Change the balance factor of p to equal
– Leave shorter true.
/

T1

p

T2

−

T1

p

• No rotations
• Height reduced

T2

deleted

CENG 213 Data Structures

31
Case 3
6.

Case 3: The balance factor of p is not equal, and the
shorter subtree was shortened.
– Rotation is needed.
– Let q be the root of the taller subtree of p. We have
three cases according to the balance factor of q.

CENG 213 Data Structures

32
Case 3a
7.

Case 3a: The balance factor of q is equal.
– Apply a single rotation
– shorter becomes false.
p



/
−

h-1

deleted

height unchanged

q

p

q



T1

h
h

T2

h

T3

h-1

CENG 213 Data Structures

T1

h

T3

T2

33
Case 3b
8.

Case 3b: The balance factor of q is the same as that of p.
– Apply a single rotation
– Set the balance factors of p and q to equal
– leave shorter as true.
height reduced


p



h-1

p

T1
h-1

deleted

q

T2

h

T3

h-1

CENG 213 Data Structures

T1

q

-

h-1

h

T3

T2

34
Case 3c
9.

Case 3c: The balance factors of p and q are opposite.
– Apply a double rotation
– set the balance factors of the new root to equal
– leave shorter as true.
height reduced


p

/

h-1

q

r

p

q

r

T1

h-1
T2

h-1
or
h-2

T3

T4
h-1

T1

CENG 213 Data Structures

T2

h-1
or
h-2

T4

T3 h-1

35
Example
Delete p.

m
p

e
c

b
a

j
d

k

h
g

n

i

s
o

l

r

u
t

f

CENG 213 Data Structures

36

Más contenido relacionado

La actualidad más candente

Percona Xtrabackup - Highly Efficient Backups
Percona Xtrabackup - Highly Efficient BackupsPercona Xtrabackup - Highly Efficient Backups
Percona Xtrabackup - Highly Efficient BackupsMydbops
 
Performance Management in Oracle 12c
Performance Management in Oracle 12cPerformance Management in Oracle 12c
Performance Management in Oracle 12cAlfredo Krieg
 
Understanding oracle rac internals part 1 - slides
Understanding oracle rac internals   part 1 - slidesUnderstanding oracle rac internals   part 1 - slides
Understanding oracle rac internals part 1 - slidesMohamed Farouk
 
Troubleshooting Tips and Tricks for Database 19c - Sangam 2019
Troubleshooting Tips and Tricks for Database 19c - Sangam 2019Troubleshooting Tips and Tricks for Database 19c - Sangam 2019
Troubleshooting Tips and Tricks for Database 19c - Sangam 2019Sandesh Rao
 
Extreme Replication - Performance Tuning Oracle GoldenGate
Extreme Replication - Performance Tuning Oracle GoldenGateExtreme Replication - Performance Tuning Oracle GoldenGate
Extreme Replication - Performance Tuning Oracle GoldenGateBobby Curtis
 
ProxySQL & PXC(Query routing and Failover Test)
ProxySQL & PXC(Query routing and Failover Test)ProxySQL & PXC(Query routing and Failover Test)
ProxySQL & PXC(Query routing and Failover Test)YoungHeon (Roy) Kim
 
Polymorphic Table Functions in SQL
Polymorphic Table Functions in SQLPolymorphic Table Functions in SQL
Polymorphic Table Functions in SQLChris Saxon
 
All about Zookeeper and ClickHouse Keeper.pdf
All about Zookeeper and ClickHouse Keeper.pdfAll about Zookeeper and ClickHouse Keeper.pdf
All about Zookeeper and ClickHouse Keeper.pdfAltinity Ltd
 
Oracle Cloud is Best for Oracle Database - High Availability
Oracle Cloud is Best for Oracle Database - High AvailabilityOracle Cloud is Best for Oracle Database - High Availability
Oracle Cloud is Best for Oracle Database - High AvailabilityMarkus Michalewicz
 
Analyzing Oracle Database hang issues using various diagnostics.
Analyzing Oracle Database hang issues using various diagnostics.Analyzing Oracle Database hang issues using various diagnostics.
Analyzing Oracle Database hang issues using various diagnostics.Ryota Watabe
 
Oracle GoldenGate 19c を使用した 簡単データベース移行ガイド_v1.0
Oracle GoldenGate 19c を使用した 簡単データベース移行ガイド_v1.0Oracle GoldenGate 19c を使用した 簡単データベース移行ガイド_v1.0
Oracle GoldenGate 19c を使用した 簡単データベース移行ガイド_v1.0オラクルエンジニア通信
 
5 Factors When Selecting a High Performance, Low Latency Database
5 Factors When Selecting a High Performance, Low Latency Database5 Factors When Selecting a High Performance, Low Latency Database
5 Factors When Selecting a High Performance, Low Latency DatabaseScyllaDB
 
Oracle RAC - New Generation
Oracle RAC - New GenerationOracle RAC - New Generation
Oracle RAC - New GenerationAnil Nair
 
How to Use EXAchk Effectively to Manage Exadata Environments
How to Use EXAchk Effectively to Manage Exadata EnvironmentsHow to Use EXAchk Effectively to Manage Exadata Environments
How to Use EXAchk Effectively to Manage Exadata EnvironmentsSandesh Rao
 
Running E-Business Suite Database on Oracle Database Appliance
Running E-Business Suite Database on Oracle Database ApplianceRunning E-Business Suite Database on Oracle Database Appliance
Running E-Business Suite Database on Oracle Database ApplianceMaris Elsins
 

La actualidad más candente (20)

Percona Xtrabackup - Highly Efficient Backups
Percona Xtrabackup - Highly Efficient BackupsPercona Xtrabackup - Highly Efficient Backups
Percona Xtrabackup - Highly Efficient Backups
 
Performance Management in Oracle 12c
Performance Management in Oracle 12cPerformance Management in Oracle 12c
Performance Management in Oracle 12c
 
Understanding oracle rac internals part 1 - slides
Understanding oracle rac internals   part 1 - slidesUnderstanding oracle rac internals   part 1 - slides
Understanding oracle rac internals part 1 - slides
 
Troubleshooting Tips and Tricks for Database 19c - Sangam 2019
Troubleshooting Tips and Tricks for Database 19c - Sangam 2019Troubleshooting Tips and Tricks for Database 19c - Sangam 2019
Troubleshooting Tips and Tricks for Database 19c - Sangam 2019
 
Extreme Replication - Performance Tuning Oracle GoldenGate
Extreme Replication - Performance Tuning Oracle GoldenGateExtreme Replication - Performance Tuning Oracle GoldenGate
Extreme Replication - Performance Tuning Oracle GoldenGate
 
ProxySQL & PXC(Query routing and Failover Test)
ProxySQL & PXC(Query routing and Failover Test)ProxySQL & PXC(Query routing and Failover Test)
ProxySQL & PXC(Query routing and Failover Test)
 
Oracle Tablespace介紹
Oracle Tablespace介紹Oracle Tablespace介紹
Oracle Tablespace介紹
 
Polymorphic Table Functions in SQL
Polymorphic Table Functions in SQLPolymorphic Table Functions in SQL
Polymorphic Table Functions in SQL
 
All about Zookeeper and ClickHouse Keeper.pdf
All about Zookeeper and ClickHouse Keeper.pdfAll about Zookeeper and ClickHouse Keeper.pdf
All about Zookeeper and ClickHouse Keeper.pdf
 
Avl tree
Avl treeAvl tree
Avl tree
 
Oracle GoldenGate R12.2 セットアップガイド
Oracle GoldenGate R12.2 セットアップガイドOracle GoldenGate R12.2 セットアップガイド
Oracle GoldenGate R12.2 セットアップガイド
 
Oracle Cloud is Best for Oracle Database - High Availability
Oracle Cloud is Best for Oracle Database - High AvailabilityOracle Cloud is Best for Oracle Database - High Availability
Oracle Cloud is Best for Oracle Database - High Availability
 
Analyzing Oracle Database hang issues using various diagnostics.
Analyzing Oracle Database hang issues using various diagnostics.Analyzing Oracle Database hang issues using various diagnostics.
Analyzing Oracle Database hang issues using various diagnostics.
 
Oracle 表格介紹
Oracle 表格介紹Oracle 表格介紹
Oracle 表格介紹
 
Oracle GoldenGate 19c を使用した 簡単データベース移行ガイド_v1.0
Oracle GoldenGate 19c を使用した 簡単データベース移行ガイド_v1.0Oracle GoldenGate 19c を使用した 簡単データベース移行ガイド_v1.0
Oracle GoldenGate 19c を使用した 簡単データベース移行ガイド_v1.0
 
5 Factors When Selecting a High Performance, Low Latency Database
5 Factors When Selecting a High Performance, Low Latency Database5 Factors When Selecting a High Performance, Low Latency Database
5 Factors When Selecting a High Performance, Low Latency Database
 
Oracle RAC - New Generation
Oracle RAC - New GenerationOracle RAC - New Generation
Oracle RAC - New Generation
 
How to Use EXAchk Effectively to Manage Exadata Environments
How to Use EXAchk Effectively to Manage Exadata EnvironmentsHow to Use EXAchk Effectively to Manage Exadata Environments
How to Use EXAchk Effectively to Manage Exadata Environments
 
Running E-Business Suite Database on Oracle Database Appliance
Running E-Business Suite Database on Oracle Database ApplianceRunning E-Business Suite Database on Oracle Database Appliance
Running E-Business Suite Database on Oracle Database Appliance
 
The PostgreSQL Query Planner
The PostgreSQL Query PlannerThe PostgreSQL Query Planner
The PostgreSQL Query Planner
 

Similar a Av ltrees (20)

9 chapter4 trees_avl
9 chapter4 trees_avl9 chapter4 trees_avl
9 chapter4 trees_avl
 
AVL TREE PREPARED BY M V BRAHMANANDA REDDY
AVL TREE PREPARED BY M V BRAHMANANDA REDDYAVL TREE PREPARED BY M V BRAHMANANDA REDDY
AVL TREE PREPARED BY M V BRAHMANANDA REDDY
 
Avl tree
Avl treeAvl tree
Avl tree
 
AVL Tree.pptx
AVL Tree.pptxAVL Tree.pptx
AVL Tree.pptx
 
AVL_Trees.ppt
AVL_Trees.pptAVL_Trees.ppt
AVL_Trees.ppt
 
Avl trees final
Avl trees finalAvl trees final
Avl trees final
 
avl.ppt
avl.pptavl.ppt
avl.ppt
 
avl.ppt
avl.pptavl.ppt
avl.ppt
 
Study about AVL Tree & Operations
Study about AVL Tree & OperationsStudy about AVL Tree & Operations
Study about AVL Tree & Operations
 
AVL Tree
AVL TreeAVL Tree
AVL Tree
 
Lecture 10 - AVL Trees.pdf
Lecture 10 - AVL Trees.pdfLecture 10 - AVL Trees.pdf
Lecture 10 - AVL Trees.pdf
 
4.10.AVLTrees[1].ppt
4.10.AVLTrees[1].ppt4.10.AVLTrees[1].ppt
4.10.AVLTrees[1].ppt
 
Sienna6bst 120411102353-phpapp02
Sienna6bst 120411102353-phpapp02Sienna6bst 120411102353-phpapp02
Sienna6bst 120411102353-phpapp02
 
Avl trees
Avl treesAvl trees
Avl trees
 
C++ UNIT4.pptx
C++ UNIT4.pptxC++ UNIT4.pptx
C++ UNIT4.pptx
 
Avl tree ppt
Avl tree pptAvl tree ppt
Avl tree ppt
 
Binary Search Trees - AVL and Red Black
Binary Search Trees - AVL and Red BlackBinary Search Trees - AVL and Red Black
Binary Search Trees - AVL and Red Black
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
 
lecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminologylecture10 date structure types of graph and terminology
lecture10 date structure types of graph and terminology
 
Lecture3
Lecture3Lecture3
Lecture3
 

Último

Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024Marel
 
Value Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsValue Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsP&CO
 
Falcon Invoice Discounting: Empowering Your Business Growth
Falcon Invoice Discounting: Empowering Your Business GrowthFalcon Invoice Discounting: Empowering Your Business Growth
Falcon Invoice Discounting: Empowering Your Business GrowthFalcon investment
 
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangaloreamitlee9823
 
Whitefield CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
Whitefield CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLWhitefield CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
Whitefield CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLkapoorjyoti4444
 
Eluru Call Girls Service ☎ ️93326-06886 ❤️‍🔥 Enjoy 24/7 Escort Service
Eluru Call Girls Service ☎ ️93326-06886 ❤️‍🔥 Enjoy 24/7 Escort ServiceEluru Call Girls Service ☎ ️93326-06886 ❤️‍🔥 Enjoy 24/7 Escort Service
Eluru Call Girls Service ☎ ️93326-06886 ❤️‍🔥 Enjoy 24/7 Escort ServiceDamini Dixit
 
Falcon Invoice Discounting: Unlock Your Business Potential
Falcon Invoice Discounting: Unlock Your Business PotentialFalcon Invoice Discounting: Unlock Your Business Potential
Falcon Invoice Discounting: Unlock Your Business PotentialFalcon investment
 
Uneak White's Personal Brand Exploration Presentation
Uneak White's Personal Brand Exploration PresentationUneak White's Personal Brand Exploration Presentation
Uneak White's Personal Brand Exploration Presentationuneakwhite
 
Falcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investorsFalcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investorsFalcon Invoice Discounting
 
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...amitlee9823
 
Call Girls Kengeri Satellite Town Just Call 👗 7737669865 👗 Top Class Call Gir...
Call Girls Kengeri Satellite Town Just Call 👗 7737669865 👗 Top Class Call Gir...Call Girls Kengeri Satellite Town Just Call 👗 7737669865 👗 Top Class Call Gir...
Call Girls Kengeri Satellite Town Just Call 👗 7737669865 👗 Top Class Call Gir...amitlee9823
 
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...rajveerescorts2022
 
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...lizamodels9
 
Cheap Rate Call Girls In Noida Sector 62 Metro 959961乂3876
Cheap Rate Call Girls In Noida Sector 62 Metro 959961乂3876Cheap Rate Call Girls In Noida Sector 62 Metro 959961乂3876
Cheap Rate Call Girls In Noida Sector 62 Metro 959961乂3876dlhescort
 
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Sheetaleventcompany
 
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 MonthsSEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 MonthsIndeedSEO
 
How to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League CityHow to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League CityEric T. Tung
 
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...Anamikakaur10
 
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...allensay1
 

Último (20)

Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024Marel Q1 2024 Investor Presentation from May 8, 2024
Marel Q1 2024 Investor Presentation from May 8, 2024
 
Value Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsValue Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and pains
 
Falcon Invoice Discounting: Empowering Your Business Growth
Falcon Invoice Discounting: Empowering Your Business GrowthFalcon Invoice Discounting: Empowering Your Business Growth
Falcon Invoice Discounting: Empowering Your Business Growth
 
(Anamika) VIP Call Girls Napur Call Now 8617697112 Napur Escorts 24x7
(Anamika) VIP Call Girls Napur Call Now 8617697112 Napur Escorts 24x7(Anamika) VIP Call Girls Napur Call Now 8617697112 Napur Escorts 24x7
(Anamika) VIP Call Girls Napur Call Now 8617697112 Napur Escorts 24x7
 
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Hebbal Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
Whitefield CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
Whitefield CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLWhitefield CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
Whitefield CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
 
Eluru Call Girls Service ☎ ️93326-06886 ❤️‍🔥 Enjoy 24/7 Escort Service
Eluru Call Girls Service ☎ ️93326-06886 ❤️‍🔥 Enjoy 24/7 Escort ServiceEluru Call Girls Service ☎ ️93326-06886 ❤️‍🔥 Enjoy 24/7 Escort Service
Eluru Call Girls Service ☎ ️93326-06886 ❤️‍🔥 Enjoy 24/7 Escort Service
 
Falcon Invoice Discounting: Unlock Your Business Potential
Falcon Invoice Discounting: Unlock Your Business PotentialFalcon Invoice Discounting: Unlock Your Business Potential
Falcon Invoice Discounting: Unlock Your Business Potential
 
Uneak White's Personal Brand Exploration Presentation
Uneak White's Personal Brand Exploration PresentationUneak White's Personal Brand Exploration Presentation
Uneak White's Personal Brand Exploration Presentation
 
Falcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investorsFalcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investors
 
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
Call Girls Electronic City Just Call 👗 7737669865 👗 Top Class Call Girl Servi...
 
Call Girls Kengeri Satellite Town Just Call 👗 7737669865 👗 Top Class Call Gir...
Call Girls Kengeri Satellite Town Just Call 👗 7737669865 👗 Top Class Call Gir...Call Girls Kengeri Satellite Town Just Call 👗 7737669865 👗 Top Class Call Gir...
Call Girls Kengeri Satellite Town Just Call 👗 7737669865 👗 Top Class Call Gir...
 
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
 
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
 
Cheap Rate Call Girls In Noida Sector 62 Metro 959961乂3876
Cheap Rate Call Girls In Noida Sector 62 Metro 959961乂3876Cheap Rate Call Girls In Noida Sector 62 Metro 959961乂3876
Cheap Rate Call Girls In Noida Sector 62 Metro 959961乂3876
 
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
 
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 MonthsSEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 Months
 
How to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League CityHow to Get Started in Social Media for Art League City
How to Get Started in Social Media for Art League City
 
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...
Call Now ☎️🔝 9332606886🔝 Call Girls ❤ Service In Bhilwara Female Escorts Serv...
 
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
 

Av ltrees

  • 1. AVL Trees CENG 213 Data Structures 1
  • 2. AVL Trees • • • • An AVL tree is a binary search tree with a balance condition. AVL is named for its inventors: Adel’son-Vel’skii and Landis AVL tree approximates the ideal tree (completely balanced tree). AVL Tree maintains a height close to the minimum. Definition: An AVL tree is a binary search tree such that for any node in the tree, the height of the left and right subtrees can differ by at most 1. CENG 213 Data Structures 2
  • 3. Figure 19.21 Two binary search trees: (a) an AVL tree; (b) not an AVL tree (unbalanced nodes are darkened) CENG 213 Data Structures 3
  • 4. Figure 19.22 Minimum tree of height H CENG 213 Data Structures 4
  • 5. Properties • The depth of a typical node in an AVL tree is very close to the optimal log N. • Consequently, all searching operations in an AVL tree have logarithmic worst-case bounds. • An update (insert or remove) in an AVL tree could destroy the balance. It must then be rebalanced before the operation can be considered complete. • After an insertion, only nodes that are on the path from the insertion point to the root can have their balances altered. CENG 213 Data Structures 5
  • 6. Rebalancing • Suppose the node to be rebalanced is X. There are 4 cases that we might have to fix (two are the mirror images of the other two): 1. 2. 3. 4. • An insertion in the left subtree of the left child of X, An insertion in the right subtree of the left child of X, An insertion in the left subtree of the right child of X, or An insertion in the right subtree of the right child of X. Balance is restored by tree rotations. CENG 213 Data Structures 6
  • 7. Balancing Operations: Rotations • Case 1 and case 4 are symmetric and requires the same operation for balance. – Cases 1,4 are handled by single rotation. • Case 2 and case 3 are symmetric and requires the same operation for balance. – Cases 2,3 are handled by double rotation. CENG 213 Data Structures 7
  • 8. Single Rotation • A single rotation switches the roles of the parent and child while maintaining the search order. • Single rotation handles the outside cases (i.e. 1 and 4). • We rotate between a node and its child. – Child becomes parent. Parent becomes right child in case 1, left child in case 4. • The result is a binary search tree that satisfies the AVL property. CENG 213 Data Structures 8
  • 9. Figure 19.23 Single rotation to fix case 1: Rotate right CENG 213 Data Structures 9
  • 10. Figure 19.26 Symmetric single rotation to fix case 4 : Rotate left CENG 213 Data Structures 10
  • 11. Figure 19.25 Single rotation fixes an AVL tree after insertion of 1. CENG 213 Data Structures 11
  • 12. Example • Start with an empty AVL tree and insert the items 3,2,1, and then 4 through 7 in sequential order. • Answer: 4 2 1 6 3 5 CENG 213 Data Structures 7 12
  • 13. Analysis • One rotation suffices to fix cases 1 and 4. • Single rotation preserves the original height: – The new height of the entire subtree is exactly the same as the height of the original subtree before the insertion. • Therefore it is enough to do rotation only at the first node, where imbalance exists, on the path from inserted node to root. • Thus the rotation takes O(1) time. • Hence insertion is O(logN) CENG 213 Data Structures 13
  • 14. Double Rotation • Single rotation does not fix the inside cases (2 and 3). • These cases require a double rotation, involving three nodes and four subtrees. CENG 213 Data Structures 14
  • 15. Figure 19.28 Single rotation does not fix case 2. CENG 213 Data Structures 15
  • 16. Left–right double rotation to fix case 2 Lift this up: first rotate left between (k1,k2), then rotate right betwen (k3,k2) CENG 213 Data Structures 16
  • 17. Left-Right Double Rotation • A left-right double rotation is equivalent to a sequence of two single rotations: – 1st rotation on the original tree: a left rotation between X’s left-child and grandchild – 2nd rotation on the new tree: a right rotation between X and its new left child. CENG 213 Data Structures 17
  • 18. Figure 19.30 Double rotation fixes AVL tree after the insertion of 5. CENG 213 Data Structures 18
  • 19. Right–Left double rotation to fix case 3. CENG 213 Data Structures 19
  • 20. Example • Insert 16, 15, 14, 13, 12, 11, 10, and 8, and 9 to the previous tree obtained in the previous single rotation example. • Answer: 7 13 4 6 2 1 3 11 9 5 8 15 12 14 16 10 CENG 213 Data Structures 20
  • 21. Node declaration for AVL trees template <class Comparable> class AvlTree; template <class Comparable> class AvlNode { Comparable element; AvlNode *left; AvlNode *right; int height; AvlNode( const Comparable & theElement, AvlNode *lt, AvlNode *rt, int h = 0 ) : element( theElement ), left( lt ), right( rt ), height( h ) { } friend class AvlTree<Comparable>; }; CENG 213 Data Structures 21
  • 22. Height template class <Comparable> int AvlTree<Comparable>::height( AvlNode<Comparable > *t) const { return t == NULL ? -1 : t->height; } CENG 213 Data Structures 22
  • 23. Single right rotation /** * Rotate binary tree node with left child. * For AVL trees, this is a single rotation for case 1. * Update heights, then set new root. */ template <class Comparable> void AvlTree<Comparable>::rotateWithLeftChild( AvlNode<Comparable> * & k2 ) const { AvlNode<Comparable> *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; k2 = k1; } CENG 213 Data Structures 23
  • 24. Double Rotation /** * Double rotate binary tree node: first left child. * with its right child; then node k3 with new left child. * For AVL trees, this is a double rotation for case 2. * Update heights, then set new root. */ template <class Comparable> void AvlTree<Comparable>::doubleWithLeftChild( AvlNode<Compa rable> * & k3 ) const { rotateWithRightChild( k3->left ); rotateWithLeftChild( k3 ); } CENG 213 Data Structures 24
  • 25. /* Internal method to insert into a subtree. * x is the item to insert. * t is the node that roots the tree. */ template <class Comparable> void AvlTree<Comparable>::insert( const Comparable & x, AvlNode<Comparable> * & t ) const { if( t == NULL ) t = new AvlNode<Comparable>( x, NULL, NULL ); else if( x < t->element ) { insert( x, t->left ); if( height( t->left ) - height( t->right ) == 2 ) if( x < t->left->element ) rotateWithLeftChild( t ); else doubleWithLeftChild( t ); } else if( t->element < x ) { insert( x, t->right ); if( height( t->right ) - height( t->left ) == 2 ) if( t->right->element < x ) rotateWithRightChild( t ); else doubleWithRightChild( t ); } else ; // Duplicate; do nothing t->height = max( height( t->left ), height( t->right ) ) + 1; } CENG 213 Data Structures 25
  • 26. AVL Tree -- Deletion • Deletion is more complicated. • We may need more than one rebalance on the path from deleted node to root. • Deletion is O(logN) CENG 213 Data Structures 26
  • 27. Deletion of a Node • Deletion of a node x from an AVL tree requires the same basic ideas, including single and double rotations, that are used for insertion. • With each node of the AVL tree is associated a balance factor that is left high, equal or right high according, respectively, as the left subtree has height greater than, equal to, or less than that of the right subtree. CENG 213 Data Structures 27
  • 28. Method 1. Reduce the problem to the case when the node x to be deleted has at most one child. – – If x has two children replace it with its immediate predecessor y under inorder traversal (the immediate successor would be just as good) Delete y from its original position, by proceeding as follows, using y in place of x in each of the following steps. CENG 213 Data Structures 28
  • 29. Method (cont.) 2. Delete the node x from the tree. – We’ll trace the effects of this change on height through all the nodes on the path from x back to the root. – We use a Boolean variable shorter to show if the height of a subtree has been shortened. – The action to be taken at each node depends on • • • 3. the value of shorter balance factor of the node sometimes the balance factor of a child of the node. shorter is initially true. The following steps are to be done for each node p on the path from the parent of x to the root, provided shorter remains true. When shorter becomes false, the algorithm terminates. CENG 213 Data Structures 29
  • 30. Case 1 4. Case 1: The current node p has balance factor equal. – Change the balance factor of p. – shorter becomes false − T1 p T2 T1 p • No rotations • Height unchanged T2 deleted CENG 213 Data Structures 30
  • 31. Case 2 5. Case 2: The balance factor of p is not equal and the taller subtree was shortened. – Change the balance factor of p to equal – Leave shorter true. / T1 p T2 − T1 p • No rotations • Height reduced T2 deleted CENG 213 Data Structures 31
  • 32. Case 3 6. Case 3: The balance factor of p is not equal, and the shorter subtree was shortened. – Rotation is needed. – Let q be the root of the taller subtree of p. We have three cases according to the balance factor of q. CENG 213 Data Structures 32
  • 33. Case 3a 7. Case 3a: The balance factor of q is equal. – Apply a single rotation – shorter becomes false. p / − h-1 deleted height unchanged q p q T1 h h T2 h T3 h-1 CENG 213 Data Structures T1 h T3 T2 33
  • 34. Case 3b 8. Case 3b: The balance factor of q is the same as that of p. – Apply a single rotation – Set the balance factors of p and q to equal – leave shorter as true. height reduced p h-1 p T1 h-1 deleted q T2 h T3 h-1 CENG 213 Data Structures T1 q - h-1 h T3 T2 34
  • 35. Case 3c 9. Case 3c: The balance factors of p and q are opposite. – Apply a double rotation – set the balance factors of the new root to equal – leave shorter as true. height reduced p / h-1 q r p q r T1 h-1 T2 h-1 or h-2 T3 T4 h-1 T1 CENG 213 Data Structures T2 h-1 or h-2 T4 T3 h-1 35