SlideShare une entreprise Scribd logo
1  sur  50
Télécharger pour lire hors ligne
Algorithms

Sandeep Kumar Poonia
Head Of Dept. CS/IT
B.E., M.Tech., UGC-NET
LM-IAENG, LM-IACSIT,LM-CSTA, LM-AIRCC, LM-SCIEI, AM-UACEE
Algorithms
AVL Tree
Balanced binary tree
● The disadvantage of a binary search tree is that its height can
●

●
●
●
●

be as large as N-1
This means that the time needed to perform insertion and
deletion and many other operations can be O(N) in the worst
case
We want a tree with small height
A binary tree with N node has height at least (log N)
Thus, our goal is to keep the height of a binary search tree
O(log N)
Such trees are called balanced binary search trees. Examples
are AVL tree, red-black tree.
Binary Search Tree - Best Time
● All BST operations are O(h), where d is tree

depth
● minimum d is h  log2Nfor a binary tree


with N nodes
■ What is the best case tree?
■ What is the worst case tree?

● So, best case running time of BST operations

is O(log N)
Binary Search Tree - Worst Time
● Worst case running time is O(N)
■ What happens when you Insert elements in
ascending order?
○ Insert: 2, 4, 6, 8, 10, 12 into an empty BST

■ Problem: Lack of “balance”:
○ compare depths of left and right subtree
■ Unbalanced degenerate tree
Balanced and unbalanced BST
1

4
2

2

5

3

1

4
4
6
3

Is this “balanced”?

5

2
1

3

5

6
7

7
Approaches to balancing trees
● Don't balance
■ May end up with some nodes very deep
● Strict balance
■ The tree must always be balanced perfectly
● Pretty good balance
■ Only allow a little out of balance
● Adjust on access
■ Self-adjusting
Balancing Binary Search Trees
● Many algorithms exist for keeping binary

search trees balanced
■ Adelson-Velskii and Landis (AVL) trees

(height-balanced trees)
■ Splay trees and other self-adjusting trees
■ B-trees and other multiway search trees
AVL Tree is…
● Named after Adelson-Velskii and Landis

● the first dynamically balanced trees to be

propose
● Binary search tree with balance condition in
which the sub-trees of each node can differ by
at most 1 in their height
Definition of a balanced tree
● Ensure the depth = O(log N)

● Take O(log N) time for searching, insertion,

and deletion
● Every node must have left & right sub-trees of
the same height
An AVL tree has the following
properties:
Sub-trees of each
node can differ by
at most 1 in their
height
2. Every sub-trees is
an AVL tree
1.
AVL tree?

YES

NO

Each left sub-tree has
height 1 greater than each
right sub-tree

Left sub-tree has height 3,
but right sub-tree has height
1
AVL tree
Height of a node
● The height of a leaf is 1. The height of a null
pointer is zero.
● The height of an internal node is the maximum
height of its children plus 1
Note that this definition of height is different from the one we
defined previously (we defined the height of a leaf as zero
previously).
AVL Trees
10

10
5

5

20
3

3
1
2
1

3

20
43
AVL Trees
12

8

4

2

16

10

6

14
AVL Tree
-1
0
0

0
0

-1

0

1

0

AVL Tree

-2
1
0

AVL Tree
0

-1
0

0

Not an AVL Tree
n(2)

3

Height of an AVL Tree

4

n(1)

● Fact: The height of an AVL tree storing n keys is O(log n).

● Proof: Let us bound n(h): the minimum number of internal nodes
●
●
●
●

of an AVL tree of height h.
We easily see that n(1) = 1 and n(2) = 2
For n > 2, an AVL tree of height h contains the root node, one AVL
subtree of height n-1 and another of height n-2.
That is, n(h) = 1 + n(h-1) + n(h-2)
Knowing n(h-1) > n(h-2), we get n(h) > 2n(h-2). So
n(h) > 2n(h-2), n(h) > 4n(h-4), n(h) > 8n(n-6), … (by induction),
n(h) > 2in(h-2i)

● Solving the base case we get: n(h) > 2 h/2-1
● Taking logarithms: h < 2log n(h) +2
● Thus the height of an AVL tree is O(log n)
AVL - Good but not Perfect
Balance
● AVL trees are height-balanced binary search

trees
● Balance factor of a node
■ height(left subtree) - height(right subtree)

● An AVL tree has balance factor calculated at

every node
■ For every node, heights of left and right subtree

can differ by no more than 1
■ Store current heights in each node
Height of an AVL Tree
● N(h) = minimum number of nodes in an AVL

tree of height h.
● Basis
■ N(0) = 1, N(1) = 2

● Induction
■ N(h) = N(h-1) + N(h-2) + 1

h

● Solution (recall Fibonacci analysis)
■ N(h) > h (  1.62)
h-1

h-2
Height of an AVL Tree
● N(h) > h (  1.62)

● Suppose we have n nodes in an AVL tree of

height h.
■ n > N(h) (because N(h) was the minimum)
■ n > h hence log n > h (relatively well balanced

tree!!)
■ h < 1.44 log2n (i.e., Find takes O(log n))
Insertion

Insert 6

Imbalance at 8
Perform rotation with 7
Deletion

Delete 4

Imbalance at 3
Perform rotation with 2

Imbalance at 5
Perform rotation with 8
Key Points
● AVL tree remain balanced by applying

rotations, therefore it guarantees O(log N)
search time in a dynamic environment
● Tree can be re-balanced in at most O(log N)
time
Searching AVL Trees
● Searching an AVL tree is exactly the same as

searching a regular binary tree
■ all descendants to the right of a node are greater

than the node
■ all descendants to the left of a node are less than
the node
Inserting in AVL Tree
● Insertion is similar to regular binary tree
■ keep going left (or right) in the tree until a null
child is reached
■ insert a new node in this position
○ an inserted node is always a leaf to start with

● Major difference from binary tree
■ must check if any of the sub-trees in the tree have
become too unbalanced
○ search from inserted node to root looking for any node

with a balance factor of ±2
Inserting in AVL Tree
● A few points about tree inserts
■ the insert will be done recursively
■ the insert call will return true if the height of the
sub-tree has changed
○ since we are doing an insert, the height of the sub-tree

can only increase
■ if insert() returns true, balance factor of current

node needs to be adjusted
○ balance factor = height(right) – height(left)
 left sub-tree increases, balance factor decreases by 1
 right sub-tree increases, balance factor increases by 1

■ if balance factor equals ±2 for any node, the sub-

tree must be rebalanced
Inserting in AVL Tree
M(-1)

E(1)

M(0)

P(0)

insert(V)

E(1)

J(0)

P(1)

J(0)

M(-1)

E(1)

M(-2)

P(0)

J(0)

V(0)

insert(L)

E(-2)

P(0)

J(1)
L(0)

This tree needs to be fixed!
Re-Balancing a Tree
● To check if a tree needs to be rebalanced
■ start at the parent of the inserted node and journey

up the tree to the root
○ if a node’s balance factor becomes ±2 need to do a

rotation in the sub-tree rooted at the node
○ once sub-tree has been re-balanced, guaranteed that the
rest of the tree is balanced as well


can just return false from the insert() method

■ 4 possible cases for re-balancing
○ only 2 of them need to be considered


other 2 are identical but in the opposite direction
Insertions in AVL Trees
Let the node that needs rebalancing be .
There are 4 cases:
Outside Cases (require single rotation) :
1. Insertion into left subtree of left child of .
2. Insertion into right subtree of right child of .
Inside Cases (require double rotation) :
3. Insertion into right subtree of left child of .
4. Insertion into left subtree of right child of .
The rebalancing is performed through four separate
rotation algorithms.
AVL Insertion: Outside Case
Consider a valid
AVL subtree

j

k

h
h

h

X

Y

Z
AVL Insertion: Outside Case

j
k
h+1

h
h

Y
X

Inserting into X
destroys the AVL
property at node j

Z
AVL Insertion: Outside Case

j
k
h+1

h
h

Y
X

Do a “right rotation”

Z
Single right rotation

j
k
h+1

h
h

Y
X

Do a “right rotation”

Z
Outside Case Completed
“Right rotation” done!
(“Left rotation” is mirror
symmetric)

k
j

h+1

h

h

X

Y

Z

AVL property has been restored!
AVL Insertion: Inside Case
Consider a valid
AVL subtree

j

k
h

X

h
h

Y

Z
AVL Insertion: Inside Case
Inserting into Y
destroys the
AVL property
at node j

j
k

h

h

X

Does “right rotation”
restore balance?

h+1

Y

Z
AVL Insertion: Inside Case

k
j

h

X

“Right rotation”
does not restore
balance… now k is
out of balance
h

h+1

Z
Y
AVL Insertion: Inside Case
Consider the structure
of subtree Y…

j

k

h

h

X

h+1

Y

Z
AVL Insertion: Inside Case

j

Y = node i and
subtrees V and W

k

h

i

h

X

h+1

h or h-1

V

W

Z
AVL Insertion: Inside Case

j

We will do a left-right
“double rotation” . . .

k
Z

i

X
V

W
Double rotation : first rotation

j

left rotation complete

i
Z

k
W
X

V
Double rotation : second
rotation

j

Now do a right rotation

i
Z

k
W
X

V
Double rotation : second
rotation
right rotation complete
Balance has been
restored

i
j

k
h

h

h or h-1

X

V

W

Z
AVL Trees Example
AVL Trees Example
AVL Trees Example
AVL Trees Example
AVL Trees Example
AVL Trees Example
Avl tree

Contenu connexe

Tendances

Tendances (20)

Avl trees
Avl treesAvl trees
Avl trees
 
Binomial heap presentation
Binomial heap presentationBinomial heap presentation
Binomial heap presentation
 
Red black tree
Red black treeRed black tree
Red black tree
 
B and B+ tree
B and B+ treeB and B+ tree
B and B+ tree
 
Binary tree
Binary treeBinary tree
Binary tree
 
Linked list
Linked listLinked list
Linked list
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
Tree in data structure
Tree in data structureTree in data structure
Tree in data structure
 
Hash table
Hash tableHash table
Hash table
 
Data Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search TreeData Structure and Algorithms Binary Search Tree
Data Structure and Algorithms Binary Search Tree
 
Hash table in data structure and algorithm
Hash table in data structure and algorithmHash table in data structure and algorithm
Hash table in data structure and algorithm
 
b+ tree
b+ treeb+ tree
b+ tree
 
Balanced Tree (AVL Tree & Red-Black Tree)
Balanced Tree (AVL Tree & Red-Black Tree)Balanced Tree (AVL Tree & Red-Black Tree)
Balanced Tree (AVL Tree & Red-Black Tree)
 
Binary trees1
Binary trees1Binary trees1
Binary trees1
 
Trees (data structure)
Trees (data structure)Trees (data structure)
Trees (data structure)
 
Data Structures (CS8391)
Data Structures (CS8391)Data Structures (CS8391)
Data Structures (CS8391)
 
Binary Tree in Data Structure
Binary Tree in Data StructureBinary Tree in Data Structure
Binary Tree in Data Structure
 
Chapter 12 ds
Chapter 12 dsChapter 12 ds
Chapter 12 ds
 
Splay Tree
Splay TreeSplay Tree
Splay Tree
 
Priority Queue in Data Structure
Priority Queue in Data StructurePriority Queue in Data Structure
Priority Queue in Data Structure
 

Similaire à Avl tree

Similaire à Avl tree (20)

Avl tree detailed
Avl tree detailedAvl tree detailed
Avl tree detailed
 
Avl trees
Avl treesAvl trees
Avl trees
 
Avl tree
Avl treeAvl tree
Avl tree
 
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
 
Lecture3
Lecture3Lecture3
Lecture3
 
AVL Tree.pptx
AVL Tree.pptxAVL Tree.pptx
AVL Tree.pptx
 
Avl tree ppt
Avl tree pptAvl tree ppt
Avl tree ppt
 
4.10.AVLTrees[1].ppt
4.10.AVLTrees[1].ppt4.10.AVLTrees[1].ppt
4.10.AVLTrees[1].ppt
 
avl.ppt
avl.pptavl.ppt
avl.ppt
 
avl.ppt
avl.pptavl.ppt
avl.ppt
 
bst trees AVL trees-red black trees spay trees
bst trees AVL trees-red black trees spay treesbst trees AVL trees-red black trees spay trees
bst trees AVL trees-red black trees spay trees
 
C++ UNIT4.pptx
C++ UNIT4.pptxC++ UNIT4.pptx
C++ UNIT4.pptx
 
Lect 13, 14 (final)AVL Tree and Rotations.pdf
Lect 13, 14 (final)AVL Tree and Rotations.pdfLect 13, 14 (final)AVL Tree and Rotations.pdf
Lect 13, 14 (final)AVL Tree and Rotations.pdf
 
Design data Analysis Avl Trees.pptx by piyush sir
Design data Analysis Avl Trees.pptx by piyush sirDesign data Analysis Avl Trees.pptx by piyush sir
Design data Analysis Avl Trees.pptx by piyush sir
 
avl insertion-rotation
avl insertion-rotationavl insertion-rotation
avl insertion-rotation
 
Trees in data structure
Trees in data structureTrees in data structure
Trees in data structure
 
Problems in parallel computations of tree functions
Problems in parallel computations of tree functionsProblems in parallel computations of tree functions
Problems in parallel computations of tree functions
 
Lecture 10 - AVL Trees.pdf
Lecture 10 - AVL Trees.pdfLecture 10 - AVL Trees.pdf
Lecture 10 - AVL Trees.pdf
 
DS_Mod4_2.pdf
DS_Mod4_2.pdfDS_Mod4_2.pdf
DS_Mod4_2.pdf
 
Red Black Trees
Red Black TreesRed Black Trees
Red Black Trees
 

Plus de Dr Sandeep Kumar Poonia

An improved memetic search in artificial bee colony algorithm
An improved memetic search in artificial bee colony algorithmAn improved memetic search in artificial bee colony algorithm
An improved memetic search in artificial bee colony algorithmDr Sandeep Kumar Poonia
 
Modified position update in spider monkey optimization algorithm
Modified position update in spider monkey optimization algorithmModified position update in spider monkey optimization algorithm
Modified position update in spider monkey optimization algorithmDr Sandeep Kumar Poonia
 
Enhanced local search in artificial bee colony algorithm
Enhanced local search in artificial bee colony algorithmEnhanced local search in artificial bee colony algorithm
Enhanced local search in artificial bee colony algorithmDr Sandeep Kumar Poonia
 
Memetic search in differential evolution algorithm
Memetic search in differential evolution algorithmMemetic search in differential evolution algorithm
Memetic search in differential evolution algorithmDr Sandeep Kumar Poonia
 
Improved onlooker bee phase in artificial bee colony algorithm
Improved onlooker bee phase in artificial bee colony algorithmImproved onlooker bee phase in artificial bee colony algorithm
Improved onlooker bee phase in artificial bee colony algorithmDr Sandeep Kumar Poonia
 
Comparative study of_hybrids_of_artificial_bee_colony_algorithm
Comparative study of_hybrids_of_artificial_bee_colony_algorithmComparative study of_hybrids_of_artificial_bee_colony_algorithm
Comparative study of_hybrids_of_artificial_bee_colony_algorithmDr Sandeep Kumar Poonia
 
A novel hybrid crossover based abc algorithm
A novel hybrid crossover based abc algorithmA novel hybrid crossover based abc algorithm
A novel hybrid crossover based abc algorithmDr Sandeep Kumar Poonia
 
Multiplication of two 3 d sparse matrices using 1d arrays and linked lists
Multiplication of two 3 d sparse matrices using 1d arrays and linked listsMultiplication of two 3 d sparse matrices using 1d arrays and linked lists
Multiplication of two 3 d sparse matrices using 1d arrays and linked listsDr Sandeep Kumar Poonia
 
Sunzip user tool for data reduction using huffman algorithm
Sunzip user tool for data reduction using huffman algorithmSunzip user tool for data reduction using huffman algorithm
Sunzip user tool for data reduction using huffman algorithmDr Sandeep Kumar Poonia
 
New Local Search Strategy in Artificial Bee Colony Algorithm
New Local Search Strategy in Artificial Bee Colony Algorithm New Local Search Strategy in Artificial Bee Colony Algorithm
New Local Search Strategy in Artificial Bee Colony Algorithm Dr Sandeep Kumar Poonia
 
Performance evaluation of different routing protocols in wsn using different ...
Performance evaluation of different routing protocols in wsn using different ...Performance evaluation of different routing protocols in wsn using different ...
Performance evaluation of different routing protocols in wsn using different ...Dr Sandeep Kumar Poonia
 
Performance evaluation of diff routing protocols in wsn using difft network p...
Performance evaluation of diff routing protocols in wsn using difft network p...Performance evaluation of diff routing protocols in wsn using difft network p...
Performance evaluation of diff routing protocols in wsn using difft network p...Dr Sandeep Kumar Poonia
 

Plus de Dr Sandeep Kumar Poonia (20)

Soft computing
Soft computingSoft computing
Soft computing
 
An improved memetic search in artificial bee colony algorithm
An improved memetic search in artificial bee colony algorithmAn improved memetic search in artificial bee colony algorithm
An improved memetic search in artificial bee colony algorithm
 
Modified position update in spider monkey optimization algorithm
Modified position update in spider monkey optimization algorithmModified position update in spider monkey optimization algorithm
Modified position update in spider monkey optimization algorithm
 
Enhanced local search in artificial bee colony algorithm
Enhanced local search in artificial bee colony algorithmEnhanced local search in artificial bee colony algorithm
Enhanced local search in artificial bee colony algorithm
 
RMABC
RMABCRMABC
RMABC
 
Memetic search in differential evolution algorithm
Memetic search in differential evolution algorithmMemetic search in differential evolution algorithm
Memetic search in differential evolution algorithm
 
Improved onlooker bee phase in artificial bee colony algorithm
Improved onlooker bee phase in artificial bee colony algorithmImproved onlooker bee phase in artificial bee colony algorithm
Improved onlooker bee phase in artificial bee colony algorithm
 
Comparative study of_hybrids_of_artificial_bee_colony_algorithm
Comparative study of_hybrids_of_artificial_bee_colony_algorithmComparative study of_hybrids_of_artificial_bee_colony_algorithm
Comparative study of_hybrids_of_artificial_bee_colony_algorithm
 
A novel hybrid crossover based abc algorithm
A novel hybrid crossover based abc algorithmA novel hybrid crossover based abc algorithm
A novel hybrid crossover based abc algorithm
 
Multiplication of two 3 d sparse matrices using 1d arrays and linked lists
Multiplication of two 3 d sparse matrices using 1d arrays and linked listsMultiplication of two 3 d sparse matrices using 1d arrays and linked lists
Multiplication of two 3 d sparse matrices using 1d arrays and linked lists
 
Sunzip user tool for data reduction using huffman algorithm
Sunzip user tool for data reduction using huffman algorithmSunzip user tool for data reduction using huffman algorithm
Sunzip user tool for data reduction using huffman algorithm
 
New Local Search Strategy in Artificial Bee Colony Algorithm
New Local Search Strategy in Artificial Bee Colony Algorithm New Local Search Strategy in Artificial Bee Colony Algorithm
New Local Search Strategy in Artificial Bee Colony Algorithm
 
A new approach of program slicing
A new approach of program slicingA new approach of program slicing
A new approach of program slicing
 
Performance evaluation of different routing protocols in wsn using different ...
Performance evaluation of different routing protocols in wsn using different ...Performance evaluation of different routing protocols in wsn using different ...
Performance evaluation of different routing protocols in wsn using different ...
 
Enhanced abc algo for tsp
Enhanced abc algo for tspEnhanced abc algo for tsp
Enhanced abc algo for tsp
 
Database aggregation using metadata
Database aggregation using metadataDatabase aggregation using metadata
Database aggregation using metadata
 
Performance evaluation of diff routing protocols in wsn using difft network p...
Performance evaluation of diff routing protocols in wsn using difft network p...Performance evaluation of diff routing protocols in wsn using difft network p...
Performance evaluation of diff routing protocols in wsn using difft network p...
 
Lecture28 tsp
Lecture28 tspLecture28 tsp
Lecture28 tsp
 
Lecture27 linear programming
Lecture27 linear programmingLecture27 linear programming
Lecture27 linear programming
 
Lecture26
Lecture26Lecture26
Lecture26
 

Dernier

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfPoh-Sun Goh
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhikauryashika82
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfAdmir Softic
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxdhanalakshmis0310
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 

Dernier (20)

How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Magic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptxMagic bus Group work1and 2 (Team 3).pptx
Magic bus Group work1and 2 (Team 3).pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 

Avl tree

  • 1. Algorithms Sandeep Kumar Poonia Head Of Dept. CS/IT B.E., M.Tech., UGC-NET LM-IAENG, LM-IACSIT,LM-CSTA, LM-AIRCC, LM-SCIEI, AM-UACEE
  • 3. Balanced binary tree ● The disadvantage of a binary search tree is that its height can ● ● ● ● ● be as large as N-1 This means that the time needed to perform insertion and deletion and many other operations can be O(N) in the worst case We want a tree with small height A binary tree with N node has height at least (log N) Thus, our goal is to keep the height of a binary search tree O(log N) Such trees are called balanced binary search trees. Examples are AVL tree, red-black tree.
  • 4. Binary Search Tree - Best Time ● All BST operations are O(h), where d is tree depth ● minimum d is h  log2Nfor a binary tree   with N nodes ■ What is the best case tree? ■ What is the worst case tree? ● So, best case running time of BST operations is O(log N)
  • 5. Binary Search Tree - Worst Time ● Worst case running time is O(N) ■ What happens when you Insert elements in ascending order? ○ Insert: 2, 4, 6, 8, 10, 12 into an empty BST ■ Problem: Lack of “balance”: ○ compare depths of left and right subtree ■ Unbalanced degenerate tree
  • 6. Balanced and unbalanced BST 1 4 2 2 5 3 1 4 4 6 3 Is this “balanced”? 5 2 1 3 5 6 7 7
  • 7. Approaches to balancing trees ● Don't balance ■ May end up with some nodes very deep ● Strict balance ■ The tree must always be balanced perfectly ● Pretty good balance ■ Only allow a little out of balance ● Adjust on access ■ Self-adjusting
  • 8. Balancing Binary Search Trees ● Many algorithms exist for keeping binary search trees balanced ■ Adelson-Velskii and Landis (AVL) trees (height-balanced trees) ■ Splay trees and other self-adjusting trees ■ B-trees and other multiway search trees
  • 9. AVL Tree is… ● Named after Adelson-Velskii and Landis ● the first dynamically balanced trees to be propose ● Binary search tree with balance condition in which the sub-trees of each node can differ by at most 1 in their height
  • 10. Definition of a balanced tree ● Ensure the depth = O(log N) ● Take O(log N) time for searching, insertion, and deletion ● Every node must have left & right sub-trees of the same height
  • 11. An AVL tree has the following properties: Sub-trees of each node can differ by at most 1 in their height 2. Every sub-trees is an AVL tree 1.
  • 12. AVL tree? YES NO Each left sub-tree has height 1 greater than each right sub-tree Left sub-tree has height 3, but right sub-tree has height 1
  • 13. AVL tree Height of a node ● The height of a leaf is 1. The height of a null pointer is zero. ● The height of an internal node is the maximum height of its children plus 1 Note that this definition of height is different from the one we defined previously (we defined the height of a leaf as zero previously).
  • 16. AVL Tree -1 0 0 0 0 -1 0 1 0 AVL Tree -2 1 0 AVL Tree 0 -1 0 0 Not an AVL Tree
  • 17. n(2) 3 Height of an AVL Tree 4 n(1) ● Fact: The height of an AVL tree storing n keys is O(log n). ● Proof: Let us bound n(h): the minimum number of internal nodes ● ● ● ● of an AVL tree of height h. We easily see that n(1) = 1 and n(2) = 2 For n > 2, an AVL tree of height h contains the root node, one AVL subtree of height n-1 and another of height n-2. That is, n(h) = 1 + n(h-1) + n(h-2) Knowing n(h-1) > n(h-2), we get n(h) > 2n(h-2). So n(h) > 2n(h-2), n(h) > 4n(h-4), n(h) > 8n(n-6), … (by induction), n(h) > 2in(h-2i) ● Solving the base case we get: n(h) > 2 h/2-1 ● Taking logarithms: h < 2log n(h) +2 ● Thus the height of an AVL tree is O(log n)
  • 18. AVL - Good but not Perfect Balance ● AVL trees are height-balanced binary search trees ● Balance factor of a node ■ height(left subtree) - height(right subtree) ● An AVL tree has balance factor calculated at every node ■ For every node, heights of left and right subtree can differ by no more than 1 ■ Store current heights in each node
  • 19. Height of an AVL Tree ● N(h) = minimum number of nodes in an AVL tree of height h. ● Basis ■ N(0) = 1, N(1) = 2 ● Induction ■ N(h) = N(h-1) + N(h-2) + 1 h ● Solution (recall Fibonacci analysis) ■ N(h) > h (  1.62) h-1 h-2
  • 20. Height of an AVL Tree ● N(h) > h (  1.62) ● Suppose we have n nodes in an AVL tree of height h. ■ n > N(h) (because N(h) was the minimum) ■ n > h hence log n > h (relatively well balanced tree!!) ■ h < 1.44 log2n (i.e., Find takes O(log n))
  • 21. Insertion Insert 6 Imbalance at 8 Perform rotation with 7
  • 22. Deletion Delete 4 Imbalance at 3 Perform rotation with 2 Imbalance at 5 Perform rotation with 8
  • 23. Key Points ● AVL tree remain balanced by applying rotations, therefore it guarantees O(log N) search time in a dynamic environment ● Tree can be re-balanced in at most O(log N) time
  • 24. Searching AVL Trees ● Searching an AVL tree is exactly the same as searching a regular binary tree ■ all descendants to the right of a node are greater than the node ■ all descendants to the left of a node are less than the node
  • 25. Inserting in AVL Tree ● Insertion is similar to regular binary tree ■ keep going left (or right) in the tree until a null child is reached ■ insert a new node in this position ○ an inserted node is always a leaf to start with ● Major difference from binary tree ■ must check if any of the sub-trees in the tree have become too unbalanced ○ search from inserted node to root looking for any node with a balance factor of ±2
  • 26. Inserting in AVL Tree ● A few points about tree inserts ■ the insert will be done recursively ■ the insert call will return true if the height of the sub-tree has changed ○ since we are doing an insert, the height of the sub-tree can only increase ■ if insert() returns true, balance factor of current node needs to be adjusted ○ balance factor = height(right) – height(left)  left sub-tree increases, balance factor decreases by 1  right sub-tree increases, balance factor increases by 1 ■ if balance factor equals ±2 for any node, the sub- tree must be rebalanced
  • 27. Inserting in AVL Tree M(-1) E(1) M(0) P(0) insert(V) E(1) J(0) P(1) J(0) M(-1) E(1) M(-2) P(0) J(0) V(0) insert(L) E(-2) P(0) J(1) L(0) This tree needs to be fixed!
  • 28. Re-Balancing a Tree ● To check if a tree needs to be rebalanced ■ start at the parent of the inserted node and journey up the tree to the root ○ if a node’s balance factor becomes ±2 need to do a rotation in the sub-tree rooted at the node ○ once sub-tree has been re-balanced, guaranteed that the rest of the tree is balanced as well  can just return false from the insert() method ■ 4 possible cases for re-balancing ○ only 2 of them need to be considered  other 2 are identical but in the opposite direction
  • 29. Insertions in AVL Trees Let the node that needs rebalancing be . There are 4 cases: Outside Cases (require single rotation) : 1. Insertion into left subtree of left child of . 2. Insertion into right subtree of right child of . Inside Cases (require double rotation) : 3. Insertion into right subtree of left child of . 4. Insertion into left subtree of right child of . The rebalancing is performed through four separate rotation algorithms.
  • 30. AVL Insertion: Outside Case Consider a valid AVL subtree j k h h h X Y Z
  • 31. AVL Insertion: Outside Case j k h+1 h h Y X Inserting into X destroys the AVL property at node j Z
  • 32. AVL Insertion: Outside Case j k h+1 h h Y X Do a “right rotation” Z
  • 33. Single right rotation j k h+1 h h Y X Do a “right rotation” Z
  • 34. Outside Case Completed “Right rotation” done! (“Left rotation” is mirror symmetric) k j h+1 h h X Y Z AVL property has been restored!
  • 35. AVL Insertion: Inside Case Consider a valid AVL subtree j k h X h h Y Z
  • 36. AVL Insertion: Inside Case Inserting into Y destroys the AVL property at node j j k h h X Does “right rotation” restore balance? h+1 Y Z
  • 37. AVL Insertion: Inside Case k j h X “Right rotation” does not restore balance… now k is out of balance h h+1 Z Y
  • 38. AVL Insertion: Inside Case Consider the structure of subtree Y… j k h h X h+1 Y Z
  • 39. AVL Insertion: Inside Case j Y = node i and subtrees V and W k h i h X h+1 h or h-1 V W Z
  • 40. AVL Insertion: Inside Case j We will do a left-right “double rotation” . . . k Z i X V W
  • 41. Double rotation : first rotation j left rotation complete i Z k W X V
  • 42. Double rotation : second rotation j Now do a right rotation i Z k W X V
  • 43. Double rotation : second rotation right rotation complete Balance has been restored i j k h h h or h-1 X V W Z