AVL Trees Section 4.4 39 AVL Tree A balanced tree Ensures log - - PowerPoint PPT Presentation

β–Ά
avl trees
SMART_READER_LITE
LIVE PREVIEW

AVL Trees Section 4.4 39 AVL Tree A balanced tree Ensures log - - PowerPoint PPT Presentation

AVL Trees Section 4.4 39 AVL Tree A balanced tree Ensures log running time for search, insert, and delete A simple and relaxed definition for balance log log : Too restrictive 40 Balanced Tree Height(null) =


slide-1
SLIDE 1

AVL Trees

Section 4.4

39

slide-2
SLIDE 2

AVL Tree

A balanced tree Ensures 𝑃 log π‘œ running time for search, insert, and delete A simple and relaxed definition for balance log π‘œ ≀ β„Ž ≀ log π‘œ : Too restrictive

40

slide-3
SLIDE 3

Balanced Tree

41

4 3 5 2 6 1 7

Height(root->left) = Height(root->right)

Too weak Height(null) = -1

slide-4
SLIDE 4

Balanced Tree

42

4 2 6 1 7

Height(node->left) = Height(node->right)

Could be impossible to satisfy

3 5

Height(null) = -1

slide-5
SLIDE 5

AVL Balance Condition

43

5 3 6 2 7 1 4

πΌπ‘“π‘—π‘•β„Žπ‘’ π‘œπ‘π‘’π‘“ β†’ π‘šπ‘“π‘”π‘’ βˆ’ πΌπ‘“π‘—π‘•β„Žπ‘’ π‘œπ‘π‘’π‘“ β†’ π‘ π‘—π‘•β„Žπ‘’ ≀ 1

Height(null) = -1

slide-6
SLIDE 6

AVL Example

44

5 2 7 1 6 3 4

Is this an AVL Tree? Yes

slide-7
SLIDE 7

AVL Example

45

5 4 6 2 7 1 3

Is this an AVL Tree? No

Violating node

slide-8
SLIDE 8

AVL Example

46

Is this an AVL Tree?

Yes

slide-9
SLIDE 9

Balancing an AVL Tree

For simplicity, we assume that we keep the height of each subtree at its root An imbalance can occur as a result of an insertion or deletion To balance an AVL tree, we carry out a rotation operation

47

slide-10
SLIDE 10

Insertion

Call BST.insert Update the height as you climb up to the root After each height update, check for an AVL tree violation and fix using rotation

48

slide-11
SLIDE 11

Violation after Insertion

49

Violating Node Case 1 Case 2 Case 3 Case 4 + New Node Cases 1 and 4 are symmetric Cases 2 and 3 are symmetric

slide-12
SLIDE 12

Case 1 – Single Rotation

50

k2 k1 Violating Node X Y Z Status upon insertion in X k2 is in violation k2 k1 X Y Z Rotation Is this a BST? Is this an AVL Tree? Yes Yes

slide-13
SLIDE 13

Case 2 – Single Rotation?

51

k2 k1 Violating Node X Y Z Status upon insertion in Y k2 is in violation k2 k1 X Y Z Single Rotation Is this a BST? Is this an AVL Tree? Yes No

slide-14
SLIDE 14

Case 2 – Double Rotation

52

k3 k1 Violating Node A B D k2 C k2 k1 A B C k3 D