SlideShare ist ein Scribd-Unternehmen logo
1 von 42
AVL Trees 
Adelson-Velskii and Landis
Binary Search Tree - Best Time 
• All BST operations are O(d), where d is 
tree depth 
• minimum d is 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) 
2 
d ëlog Nû 2 =
Binary Search Tree - Worst Time 
• Worst case running time is O(N) 
› What happens when you Insert elements in 
3 
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 
4 
4 
2 5 
1 3 
1 
5 
2 
4 
3 
7 
6 
4 
2 6 
1 3 5 7 
Is this “balanced”?
Approaches to balancing trees 
• Don't balance 
5 
› 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
6 
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
7 
Perfect Balance 
• Want a complete tree after every operation 
› tree is full except possibly in the lower right 
• This is expensive 
› For example, insert 2 in the tree on the left and 
then rebuild as a complete tree 
Insert 2 & 
complete tree 
6 
4 9 
1 5 8 
5 
2 8 
1 4 6 9
8 
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
9 
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 
h 
› N(h) = N(h-1) + N(h-2) + 1 
• Solution (recall Fibonacci analysis) 
› N(h) > fh (f » 1.62) h-1 h-2
10 
Height of an AVL Tree 
• N(h) > fh (f » 1.62) 
• Suppose we have n nodes in an AVL 
tree of height h. 
› n > N(h) (because N(h) was the minimum) 
› n > fh hence logf n > h (relatively well 
balanced tree!!) 
› h < 1.44 log2n (i.e., Find takes O(logn))
11 
Node Heights 
Tree A (AVL) Tree B (AVL) 
height=2 BF=1-0=1 
0 1 
height of node = h 
balance factor = hleft-hright 
empty height = -1 
1 
2 
0 0 
0 
6 
4 9 
1 5 8 
1 
0 0 
6 
4 9 
1 5
12 
Node Heights after Insert 7 
1 1 
height of node = h 
balance factor = hleft-hright 
empty height = -1 
2 
3 
0 0 
1 
6 
4 9 
1 5 8 
0 
2 
0 
6 
1 
4 9 
1 5 
07 
07 
balance factor 
1-(-1) = 2 
-1 
Tree A (AVL) Tree B (not AVL)
Insert and Rotation in AVL Trees 
• Insert operation may cause balance factor 
to become 2 or –2 for some node 
› only nodes on the path from insertion point to 
root node have possibly changed in height 
› So after the Insert, go back up to the root 
node by node, updating heights 
› If a new balance factor is 2 or –2, adjust tree 
by rotation around the node 
13
14 
Single Rotation in an AVL Tree 
2 
2 
1 
0 0 
1 
6 
4 9 
1 5 8 
07 
0 
1 
0 
2 
0 
6 
1 
4 
9 
8 
1 5 
07
15 
Insertions in AVL Trees 
Let the node that needs rebalancing be a. 
There are 4 cases: 
Outside Cases (require single rotation) : 
1. Insertion into left subtree of left child of a. 
2. Insertion into right subtree of right child of a. 
Inside Cases (require double rotation) : 
3. Insertion into right subtree of left child of a. 
4. Insertion into left subtree of right child of a. 
The rebalancing is performed through four 
separate rotation algorithms.
16 
AVL Insertion: Outside Case 
j 
k 
X Y 
Z 
Consider a valid 
AVL subtree 
h 
h h
17 
AVL Insertion: Outside Case 
j 
k 
X 
Y 
Z 
Inserting into X 
destroys the AVL 
property at node j 
h 
h+1 h
18 
AVL Insertion: Outside Case 
j 
k 
X 
Y 
Do a “right rotation” 
Z 
h 
h+1 h
19 
Single right rotation 
j 
k 
X 
Y 
Do a “right rotation” 
Z 
h 
h+1 h
“Right rotation” done! 
(“Left rotation” is mirror 
symmetric) 
20 
Outside Case Completed 
j 
k 
X Y Z 
h 
AVL property has been restored! 
h+1 
h
21 
AVL Insertion: Inside Case 
j 
k 
X Y 
Z 
Consider a valid 
AVL subtree 
h 
h h
Does “right rotation” 
restore balance? 
22 
AVL Insertion: Inside Case 
Inserting into Y 
destroys the 
AVL property 
at node j 
j 
k 
X 
Y 
Z 
h 
h h+1
23 
AVL Insertion: Inside Case 
j 
k 
X 
Y 
“Right rotation” 
does not restore 
balance… now k is 
out of balance 
h+1 h 
Z 
h
24 
AVL Insertion: Inside Case 
Consider the structure 
of subtree Y… j 
k 
X 
Y 
Z 
h 
h h+1
25 
AVL Insertion: Inside Case 
j 
k 
X 
V 
Z 
W 
i 
Y = node i and 
subtrees V and W 
h 
h h+1 
h or h-1
26 
AVL Insertion: Inside Case 
j 
k 
X 
V 
Z 
W 
i 
We will do a left-right 
“double rotation” . . . 
h h or h-1 
h
27 
Double rotation : first rotation 
j 
k 
X V 
Z 
W 
i 
left rotation complete 
h 
h or h-1 
h or h-1 
h
Double rotation : second rotation 
28 
j 
k 
X V 
Z 
W 
i 
Now do a right rotation 
h 
h 
h or h-1 
h or h-1
Double rotation : second rotation 
right rotation complete 
Balance has been 
restored 
29 
X 
i 
k j 
V W Z 
h h or h-1 h
30 
Implementation 
balance (1,0,-1) 
key 
left right 
No need to keep the height; just the difference in height, 
i.e. the balance factor; this has to be modified on the path of 
insertion even if you don’t perform rotations 
Once you have performed a rotation (single or double) you won’t 
need to go back up the tree
31 
Single Rotation 
RotateFromRight(n : reference node pointer) { 
p : node pointer; 
p := n.right; 
n 
n.right := p.left; 
p.left := n; 
n := p 
} 
You also need to 
X 
modify the heights 
or balance factors 
of n and p 
Y Z 
Insert
32 
Double Rotation 
• Implement Double Rotation in two lines. 
DoubleRotateFromRight(n : reference node pointer) { 
???? 
n 
} 
X 
V W 
Z
33 
Insertion in AVL Trees 
• Insert at the leaf (as for all BST) 
› only nodes on the path from insertion point to 
root node have possibly changed in height 
› So after the Insert, go back up to the root 
node by node, updating heights 
› If a new balance factor is 2 or –2, adjust tree 
by rotation around the node
34 
Insert in BST 
Insert(T : reference tree pointer, x : element) : 
integer { 
if T = null then 
T := new tree; T.data := x; return 1;//the 
links to 
//children are null 
case 
T.data = x : return 0; //Duplicate do nothing 
T.data > x : return Insert(T.left, x); 
T.data < x : return Insert(T.right, x); 
endcase 
}
35 
Insert in AVL trees 
Insert(T : reference tree pointer, x : element) : { 
if T = null then 
{T := new tree; T.data := x; height := 0; return;} 
case 
T.data = x : return ; //Duplicate do nothing 
T.data > x : Insert(T.left, x); 
if ((height(T.left)- height(T.right)) = 2){ 
if (T.left.data > x ) then //outside case 
T = RotatefromLeft (T); 
else //inside case 
T = DoubleRotatefromLeft (T);} 
T.data < x : Insert(T.right, x); 
code similar to the left case 
Endcase 
T.height := max(height(T.left),height(T.right)) +1; 
return; 
}
Example of Insertions in an AVL Tree 
36 
1 
0 
2 
20 
10 30 
25 
0 
0 
35 
Insert 5, 40
Example of Insertions in an AVL Tree 
0 1 
37 
1 
0 
2 
20 
10 30 
25 
1 
0 
35 
0 
5 
20 
10 30 
25 
1 
5 35 
40 
0 
0 
2 
3 
Now Insert 45
Single rotation (outside case) 
1 
0 0 
38 
2 
0 
3 
20 
10 30 
25 
1 
2 
35 
0 
5 
20 
10 30 
25 
1 
5 40 
40 
0 
0 
0 
1 
2 
3 
45 
Imbalance 
35 45 
Now Insert 34
0 
1 
39 
Double rotation (inside case) 
3 
0 
3 
20 
10 30 
25 
1 
2 
40 
0 
5 
20 
10 35 
30 
1 
5 40 
45 
0 1 
2 
3 
Imbalance 
45 
Insertion of 34 
35 
34 
0 
0 
1 0 25 34
40 
AVL Tree Deletion 
• Similar but more complex than insertion 
› Rotations and double rotations needed to 
rebalance 
› Imbalance may propagate upward so that 
many rotations may be needed.
Pros and Cons of AVL Trees 
Arguments for AVL trees: 
1. Search is O(log N) since AVL trees are always balanced. 
2. Insertion and deletions are also O(logn) 
3. The height balancing adds no more than a constant factor to the 
41 
speed of insertion. 
Arguments against using AVL trees: 
1. Difficult to program & debug; more space for balance factor. 
2. Asymptotically faster but rebalancing costs time. 
3. Most large searches are done in database systems on disk and use 
other structures (e.g. B-trees). 
4. May be OK to have O(N) for a single operation if total run time for 
many consecutive operations is fast (e.g. Splay trees).
42 
Double Rotation Solution 
DoubleRotateFromRight(n : reference node pointer) { 
RotateFromLeft(n.right); 
RotateFromRight(n); 
} 
X 
n 
V W 
Z

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

AVL Trees
AVL TreesAVL Trees
AVL Trees
 
AVL Tree
AVL TreeAVL Tree
AVL Tree
 
AVL tree ( Balanced Binary Search Tree)-Data Structure
AVL tree ( Balanced Binary Search Tree)-Data StructureAVL tree ( Balanced Binary Search Tree)-Data Structure
AVL tree ( Balanced Binary Search Tree)-Data Structure
 
Avltrees
AvltreesAvltrees
Avltrees
 
Avl trees
Avl treesAvl trees
Avl trees
 
Computer notes - AVL Tree
Computer notes - AVL TreeComputer notes - AVL Tree
Computer notes - AVL Tree
 
AVL Tree
AVL TreeAVL Tree
AVL Tree
 
Avl trees
Avl treesAvl trees
Avl trees
 
Lecture 10 data structures and algorithms
Lecture 10 data structures and algorithmsLecture 10 data structures and algorithms
Lecture 10 data structures and algorithms
 
Balance tree. Short overview
Balance tree. Short overviewBalance tree. Short overview
Balance tree. Short overview
 
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
 
Binary Trees
Binary TreesBinary Trees
Binary Trees
 
Trees
TreesTrees
Trees
 
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)
 
Tree
TreeTree
Tree
 
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
358 33 powerpoint-slides_11-efficient-binary-trees_chapter-11
 
Avl trees 2
Avl trees 2Avl trees 2
Avl trees 2
 
Splay tree
Splay treeSplay tree
Splay tree
 
Splay Tree
Splay TreeSplay Tree
Splay Tree
 
Tree traversal techniques
Tree traversal techniquesTree traversal techniques
Tree traversal techniques
 

Andere mochten auch (20)

Avl trees
Avl treesAvl trees
Avl trees
 
Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures Trees, Binary Search Tree, AVL Tree in Data Structures
Trees, Binary Search Tree, AVL Tree in Data Structures
 
Multi ways trees
Multi ways treesMulti ways trees
Multi ways trees
 
Avl Tree Implementation
Avl Tree ImplementationAvl Tree Implementation
Avl Tree Implementation
 
Avl tree
Avl treeAvl tree
Avl tree
 
Data Structures : AVL Trees
Data Structures : AVL TreesData Structures : AVL Trees
Data Structures : AVL Trees
 
2-3 Tree
2-3 Tree2-3 Tree
2-3 Tree
 
Avl tree by umesh
Avl tree by umeshAvl tree by umesh
Avl tree by umesh
 
b+tree
b+treeb+tree
b+tree
 
M-tree Algorithm
M-tree AlgorithmM-tree Algorithm
M-tree Algorithm
 
Binary Search Tree and AVL
Binary Search Tree and AVLBinary Search Tree and AVL
Binary Search Tree and AVL
 
Hash tables
Hash tablesHash tables
Hash tables
 
10.m way search tree
10.m way search tree10.m way search tree
10.m way search tree
 
Nikhat b+ trees ppt
Nikhat b+ trees pptNikhat b+ trees ppt
Nikhat b+ trees ppt
 
B+ trees
B+ treesB+ trees
B+ trees
 
Coal7 segmentation in Assembly Programming
Coal7 segmentation in Assembly ProgrammingCoal7 segmentation in Assembly Programming
Coal7 segmentation in Assembly Programming
 
B trees and_b__trees
B trees and_b__treesB trees and_b__trees
B trees and_b__trees
 
08 Hash Tables
08 Hash Tables08 Hash Tables
08 Hash Tables
 
Red black trees
Red black treesRed black trees
Red black trees
 
B trees
B treesB trees
B trees
 

Ähnlich wie Avl tree

4.10.AVLTrees[1].ppt
4.10.AVLTrees[1].ppt4.10.AVLTrees[1].ppt
4.10.AVLTrees[1].pptomkarbhabal
 
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 sir22001003058
 
AVL_Trees using DSA concepts and how to do
AVL_Trees using DSA concepts and how to doAVL_Trees using DSA concepts and how to do
AVL_Trees using DSA concepts and how to dolokaprasaadvs
 
avl insertion-rotation
avl insertion-rotationavl insertion-rotation
avl insertion-rotationXad Kuain
 
9 chapter4 trees_avl
9 chapter4 trees_avl9 chapter4 trees_avl
9 chapter4 trees_avlSSE_AndyLi
 
Adelson velskii Landis rotations based on
Adelson velskii Landis rotations based onAdelson velskii Landis rotations based on
Adelson velskii Landis rotations based onbanupriyar5
 
Data structures trees and graphs - AVL tree.pptx
Data structures trees and graphs - AVL  tree.pptxData structures trees and graphs - AVL  tree.pptx
Data structures trees and graphs - AVL tree.pptxMalligaarjunanN
 
AVL Tree.pptx
AVL Tree.pptxAVL Tree.pptx
AVL Tree.pptxTrad5
 
Lecture 10 - AVL Trees.pdf
Lecture 10 - AVL Trees.pdfLecture 10 - AVL Trees.pdf
Lecture 10 - AVL Trees.pdfSanghdipUdrake
 
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.pdfMuhammadUmerIhtisham
 

Ähnlich wie Avl tree (20)

Lecture3
Lecture3Lecture3
Lecture3
 
avl.ppt
avl.pptavl.ppt
avl.ppt
 
avl.ppt
avl.pptavl.ppt
avl.ppt
 
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
 
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 Tree Data Structure
AVL Tree Data StructureAVL Tree Data Structure
AVL Tree Data Structure
 
AVL_Trees using DSA concepts and how to do
AVL_Trees using DSA concepts and how to doAVL_Trees using DSA concepts and how to do
AVL_Trees using DSA concepts and how to do
 
avl insertion-rotation
avl insertion-rotationavl insertion-rotation
avl insertion-rotation
 
9 chapter4 trees_avl
9 chapter4 trees_avl9 chapter4 trees_avl
9 chapter4 trees_avl
 
Adelson velskii Landis rotations based on
Adelson velskii Landis rotations based onAdelson velskii Landis rotations based on
Adelson velskii Landis rotations based on
 
Data structures trees and graphs - AVL tree.pptx
Data structures trees and graphs - AVL  tree.pptxData structures trees and graphs - AVL  tree.pptx
Data structures trees and graphs - AVL tree.pptx
 
Avl tree ppt
Avl tree pptAvl tree ppt
Avl tree ppt
 
Ie
IeIe
Ie
 
AVL Tree.pptx
AVL Tree.pptxAVL Tree.pptx
AVL Tree.pptx
 
AVL Tree.ppt
AVL Tree.pptAVL Tree.ppt
AVL Tree.ppt
 
Lecture 10 - AVL Trees.pdf
Lecture 10 - AVL Trees.pdfLecture 10 - AVL Trees.pdf
Lecture 10 - AVL Trees.pdf
 
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
 
4. avl
4. avl4. avl
4. avl
 
L15-clean.pptx
L15-clean.pptxL15-clean.pptx
L15-clean.pptx
 

Mehr von Van Pham

Thi cong da hoa cuong o tphcm thien loc phat
Thi cong da hoa cuong o tphcm thien loc phatThi cong da hoa cuong o tphcm thien loc phat
Thi cong da hoa cuong o tphcm thien loc phatVan Pham
 
Cửa hàng bán đồ chơi xe máy ở TPHCM - Hoàng Phúc Decal
Cửa hàng bán đồ chơi xe máy ở TPHCM - Hoàng Phúc DecalCửa hàng bán đồ chơi xe máy ở TPHCM - Hoàng Phúc Decal
Cửa hàng bán đồ chơi xe máy ở TPHCM - Hoàng Phúc DecalVan Pham
 
Giao trinh co so du lieu can ban
Giao trinh co so du lieu can banGiao trinh co so du lieu can ban
Giao trinh co so du lieu can banVan Pham
 
Lect15 cloud
Lect15 cloudLect15 cloud
Lect15 cloudVan Pham
 
172506 633746925739945000
172506 633746925739945000172506 633746925739945000
172506 633746925739945000Van Pham
 
Bao cao thuc tap - Điện toán đám mây
Bao cao thuc tap - Điện toán đám mâyBao cao thuc tap - Điện toán đám mây
Bao cao thuc tap - Điện toán đám mâyVan Pham
 
Bai 02 active directory
Bai 02   active directoryBai 02   active directory
Bai 02 active directoryVan Pham
 
Gioi thieu va cac lenh tren console
Gioi thieu va cac lenh tren consoleGioi thieu va cac lenh tren console
Gioi thieu va cac lenh tren consoleVan Pham
 
Bai 08 quan ly in an
Bai 08   quan ly in anBai 08   quan ly in an
Bai 08 quan ly in anVan Pham
 
Bai 07 tao quan ly thu muc
Bai 07   tao quan ly thu mucBai 07   tao quan ly thu muc
Bai 07 tao quan ly thu mucVan Pham
 
Bai 06 quan ly dia
Bai 06   quan ly diaBai 06   quan ly dia
Bai 06 quan ly diaVan Pham
 
Bai 05 chinh sach nhom
Bai 05   chinh sach nhomBai 05   chinh sach nhom
Bai 05 chinh sach nhomVan Pham
 
Bai 04 chinh sach he thong
Bai 04   chinh sach he thongBai 04   chinh sach he thong
Bai 04 chinh sach he thongVan Pham
 
Bai 03 quan ly tai khoan nguoi dung
Bai 03   quan ly tai khoan nguoi dungBai 03   quan ly tai khoan nguoi dung
Bai 03 quan ly tai khoan nguoi dungVan Pham
 
Bai 01 gioi thieu cai dat
Bai 01   gioi thieu cai datBai 01   gioi thieu cai dat
Bai 01 gioi thieu cai datVan Pham
 
Bai12 too ls-kiemtra-ktrpm@softtesting-nntu
Bai12 too ls-kiemtra-ktrpm@softtesting-nntuBai12 too ls-kiemtra-ktrpm@softtesting-nntu
Bai12 too ls-kiemtra-ktrpm@softtesting-nntuVan Pham
 
Bai11 quan ly-kiemtra-ktrpm@softtesting-nntu
Bai11 quan ly-kiemtra-ktrpm@softtesting-nntuBai11 quan ly-kiemtra-ktrpm@softtesting-nntu
Bai11 quan ly-kiemtra-ktrpm@softtesting-nntuVan Pham
 
Bai10 lap tailieukiemtra-k-trpm@softtesting-nntu
Bai10 lap tailieukiemtra-k-trpm@softtesting-nntuBai10 lap tailieukiemtra-k-trpm@softtesting-nntu
Bai10 lap tailieukiemtra-k-trpm@softtesting-nntuVan Pham
 

Mehr von Van Pham (20)

Thi cong da hoa cuong o tphcm thien loc phat
Thi cong da hoa cuong o tphcm thien loc phatThi cong da hoa cuong o tphcm thien loc phat
Thi cong da hoa cuong o tphcm thien loc phat
 
Cửa hàng bán đồ chơi xe máy ở TPHCM - Hoàng Phúc Decal
Cửa hàng bán đồ chơi xe máy ở TPHCM - Hoàng Phúc DecalCửa hàng bán đồ chơi xe máy ở TPHCM - Hoàng Phúc Decal
Cửa hàng bán đồ chơi xe máy ở TPHCM - Hoàng Phúc Decal
 
Giao trinh co so du lieu can ban
Giao trinh co so du lieu can banGiao trinh co so du lieu can ban
Giao trinh co so du lieu can ban
 
Quy tắc
Quy tắcQuy tắc
Quy tắc
 
Lect15 cloud
Lect15 cloudLect15 cloud
Lect15 cloud
 
Session1
Session1Session1
Session1
 
172506 633746925739945000
172506 633746925739945000172506 633746925739945000
172506 633746925739945000
 
Bao cao thuc tap - Điện toán đám mây
Bao cao thuc tap - Điện toán đám mâyBao cao thuc tap - Điện toán đám mây
Bao cao thuc tap - Điện toán đám mây
 
Bai 02 active directory
Bai 02   active directoryBai 02   active directory
Bai 02 active directory
 
Gioi thieu va cac lenh tren console
Gioi thieu va cac lenh tren consoleGioi thieu va cac lenh tren console
Gioi thieu va cac lenh tren console
 
Bai 08 quan ly in an
Bai 08   quan ly in anBai 08   quan ly in an
Bai 08 quan ly in an
 
Bai 07 tao quan ly thu muc
Bai 07   tao quan ly thu mucBai 07   tao quan ly thu muc
Bai 07 tao quan ly thu muc
 
Bai 06 quan ly dia
Bai 06   quan ly diaBai 06   quan ly dia
Bai 06 quan ly dia
 
Bai 05 chinh sach nhom
Bai 05   chinh sach nhomBai 05   chinh sach nhom
Bai 05 chinh sach nhom
 
Bai 04 chinh sach he thong
Bai 04   chinh sach he thongBai 04   chinh sach he thong
Bai 04 chinh sach he thong
 
Bai 03 quan ly tai khoan nguoi dung
Bai 03   quan ly tai khoan nguoi dungBai 03   quan ly tai khoan nguoi dung
Bai 03 quan ly tai khoan nguoi dung
 
Bai 01 gioi thieu cai dat
Bai 01   gioi thieu cai datBai 01   gioi thieu cai dat
Bai 01 gioi thieu cai dat
 
Bai12 too ls-kiemtra-ktrpm@softtesting-nntu
Bai12 too ls-kiemtra-ktrpm@softtesting-nntuBai12 too ls-kiemtra-ktrpm@softtesting-nntu
Bai12 too ls-kiemtra-ktrpm@softtesting-nntu
 
Bai11 quan ly-kiemtra-ktrpm@softtesting-nntu
Bai11 quan ly-kiemtra-ktrpm@softtesting-nntuBai11 quan ly-kiemtra-ktrpm@softtesting-nntu
Bai11 quan ly-kiemtra-ktrpm@softtesting-nntu
 
Bai10 lap tailieukiemtra-k-trpm@softtesting-nntu
Bai10 lap tailieukiemtra-k-trpm@softtesting-nntuBai10 lap tailieukiemtra-k-trpm@softtesting-nntu
Bai10 lap tailieukiemtra-k-trpm@softtesting-nntu
 

Kürzlich hochgeladen

PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 

Kürzlich hochgeladen (20)

PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 

Avl tree

  • 2. Binary Search Tree - Best Time • All BST operations are O(d), where d is tree depth • minimum d is 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) 2 d ëlog Nû 2 =
  • 3. Binary Search Tree - Worst Time • Worst case running time is O(N) › What happens when you Insert elements in 3 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
  • 4. Balanced and unbalanced BST 4 4 2 5 1 3 1 5 2 4 3 7 6 4 2 6 1 3 5 7 Is this “balanced”?
  • 5. Approaches to balancing trees • Don't balance 5 › 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
  • 6. 6 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
  • 7. 7 Perfect Balance • Want a complete tree after every operation › tree is full except possibly in the lower right • This is expensive › For example, insert 2 in the tree on the left and then rebuild as a complete tree Insert 2 & complete tree 6 4 9 1 5 8 5 2 8 1 4 6 9
  • 8. 8 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
  • 9. 9 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 h › N(h) = N(h-1) + N(h-2) + 1 • Solution (recall Fibonacci analysis) › N(h) > fh (f » 1.62) h-1 h-2
  • 10. 10 Height of an AVL Tree • N(h) > fh (f » 1.62) • Suppose we have n nodes in an AVL tree of height h. › n > N(h) (because N(h) was the minimum) › n > fh hence logf n > h (relatively well balanced tree!!) › h < 1.44 log2n (i.e., Find takes O(logn))
  • 11. 11 Node Heights Tree A (AVL) Tree B (AVL) height=2 BF=1-0=1 0 1 height of node = h balance factor = hleft-hright empty height = -1 1 2 0 0 0 6 4 9 1 5 8 1 0 0 6 4 9 1 5
  • 12. 12 Node Heights after Insert 7 1 1 height of node = h balance factor = hleft-hright empty height = -1 2 3 0 0 1 6 4 9 1 5 8 0 2 0 6 1 4 9 1 5 07 07 balance factor 1-(-1) = 2 -1 Tree A (AVL) Tree B (not AVL)
  • 13. Insert and Rotation in AVL Trees • Insert operation may cause balance factor to become 2 or –2 for some node › only nodes on the path from insertion point to root node have possibly changed in height › So after the Insert, go back up to the root node by node, updating heights › If a new balance factor is 2 or –2, adjust tree by rotation around the node 13
  • 14. 14 Single Rotation in an AVL Tree 2 2 1 0 0 1 6 4 9 1 5 8 07 0 1 0 2 0 6 1 4 9 8 1 5 07
  • 15. 15 Insertions in AVL Trees Let the node that needs rebalancing be a. There are 4 cases: Outside Cases (require single rotation) : 1. Insertion into left subtree of left child of a. 2. Insertion into right subtree of right child of a. Inside Cases (require double rotation) : 3. Insertion into right subtree of left child of a. 4. Insertion into left subtree of right child of a. The rebalancing is performed through four separate rotation algorithms.
  • 16. 16 AVL Insertion: Outside Case j k X Y Z Consider a valid AVL subtree h h h
  • 17. 17 AVL Insertion: Outside Case j k X Y Z Inserting into X destroys the AVL property at node j h h+1 h
  • 18. 18 AVL Insertion: Outside Case j k X Y Do a “right rotation” Z h h+1 h
  • 19. 19 Single right rotation j k X Y Do a “right rotation” Z h h+1 h
  • 20. “Right rotation” done! (“Left rotation” is mirror symmetric) 20 Outside Case Completed j k X Y Z h AVL property has been restored! h+1 h
  • 21. 21 AVL Insertion: Inside Case j k X Y Z Consider a valid AVL subtree h h h
  • 22. Does “right rotation” restore balance? 22 AVL Insertion: Inside Case Inserting into Y destroys the AVL property at node j j k X Y Z h h h+1
  • 23. 23 AVL Insertion: Inside Case j k X Y “Right rotation” does not restore balance… now k is out of balance h+1 h Z h
  • 24. 24 AVL Insertion: Inside Case Consider the structure of subtree Y… j k X Y Z h h h+1
  • 25. 25 AVL Insertion: Inside Case j k X V Z W i Y = node i and subtrees V and W h h h+1 h or h-1
  • 26. 26 AVL Insertion: Inside Case j k X V Z W i We will do a left-right “double rotation” . . . h h or h-1 h
  • 27. 27 Double rotation : first rotation j k X V Z W i left rotation complete h h or h-1 h or h-1 h
  • 28. Double rotation : second rotation 28 j k X V Z W i Now do a right rotation h h h or h-1 h or h-1
  • 29. Double rotation : second rotation right rotation complete Balance has been restored 29 X i k j V W Z h h or h-1 h
  • 30. 30 Implementation balance (1,0,-1) key left right No need to keep the height; just the difference in height, i.e. the balance factor; this has to be modified on the path of insertion even if you don’t perform rotations Once you have performed a rotation (single or double) you won’t need to go back up the tree
  • 31. 31 Single Rotation RotateFromRight(n : reference node pointer) { p : node pointer; p := n.right; n n.right := p.left; p.left := n; n := p } You also need to X modify the heights or balance factors of n and p Y Z Insert
  • 32. 32 Double Rotation • Implement Double Rotation in two lines. DoubleRotateFromRight(n : reference node pointer) { ???? n } X V W Z
  • 33. 33 Insertion in AVL Trees • Insert at the leaf (as for all BST) › only nodes on the path from insertion point to root node have possibly changed in height › So after the Insert, go back up to the root node by node, updating heights › If a new balance factor is 2 or –2, adjust tree by rotation around the node
  • 34. 34 Insert in BST Insert(T : reference tree pointer, x : element) : integer { if T = null then T := new tree; T.data := x; return 1;//the links to //children are null case T.data = x : return 0; //Duplicate do nothing T.data > x : return Insert(T.left, x); T.data < x : return Insert(T.right, x); endcase }
  • 35. 35 Insert in AVL trees Insert(T : reference tree pointer, x : element) : { if T = null then {T := new tree; T.data := x; height := 0; return;} case T.data = x : return ; //Duplicate do nothing T.data > x : Insert(T.left, x); if ((height(T.left)- height(T.right)) = 2){ if (T.left.data > x ) then //outside case T = RotatefromLeft (T); else //inside case T = DoubleRotatefromLeft (T);} T.data < x : Insert(T.right, x); code similar to the left case Endcase T.height := max(height(T.left),height(T.right)) +1; return; }
  • 36. Example of Insertions in an AVL Tree 36 1 0 2 20 10 30 25 0 0 35 Insert 5, 40
  • 37. Example of Insertions in an AVL Tree 0 1 37 1 0 2 20 10 30 25 1 0 35 0 5 20 10 30 25 1 5 35 40 0 0 2 3 Now Insert 45
  • 38. Single rotation (outside case) 1 0 0 38 2 0 3 20 10 30 25 1 2 35 0 5 20 10 30 25 1 5 40 40 0 0 0 1 2 3 45 Imbalance 35 45 Now Insert 34
  • 39. 0 1 39 Double rotation (inside case) 3 0 3 20 10 30 25 1 2 40 0 5 20 10 35 30 1 5 40 45 0 1 2 3 Imbalance 45 Insertion of 34 35 34 0 0 1 0 25 34
  • 40. 40 AVL Tree Deletion • Similar but more complex than insertion › Rotations and double rotations needed to rebalance › Imbalance may propagate upward so that many rotations may be needed.
  • 41. Pros and Cons of AVL Trees Arguments for AVL trees: 1. Search is O(log N) since AVL trees are always balanced. 2. Insertion and deletions are also O(logn) 3. The height balancing adds no more than a constant factor to the 41 speed of insertion. Arguments against using AVL trees: 1. Difficult to program & debug; more space for balance factor. 2. Asymptotically faster but rebalancing costs time. 3. Most large searches are done in database systems on disk and use other structures (e.g. B-trees). 4. May be OK to have O(N) for a single operation if total run time for many consecutive operations is fast (e.g. Splay trees).
  • 42. 42 Double Rotation Solution DoubleRotateFromRight(n : reference node pointer) { RotateFromLeft(n.right); RotateFromRight(n); } X n V W Z