Presentation is loading. Please wait.

Presentation is loading. Please wait.

Balanced Binary Search Trees

Similar presentations


Presentation on theme: "Balanced Binary Search Trees"— Presentation transcript:

1 Balanced Binary Search Trees
CS-2851 Dr. Mark L. Hornick

2 For any balanced binary search tree, searching, inserting and deleting have worstTime(n) that is logarithmic in n But insertions and deletions can result in a tree that is highly unbalanced O(log2 n) performance drifts toward O(n) A BST is balanced only if if its height is logarithmic in n such that H = 1+Math.floor(log2(n)) N=8, h= 1+floor(log2(8)) N=5, h > 1+floor(log2(5) ) CS-2851 Dr. Mark L. Hornick

3 An AVL tree is a balanced BST that either is empty or in which…
Heights between left and right subtrees differs by only 1 The left and right subtrees are also AVL trees. CS-2851 Dr. Mark L. Hornick

4 Another (balanced) AVL Tree
20 30 10 35 5 32 CS-2851 Dr. Mark L. Hornick

5 More AVL Tree examples CS-2851 Dr. Mark L. Hornick

6 Non-AVL Tree examples CS-2851 Dr. Mark L. Hornick

7 Balance can be maintained through rotations
Rotation: an adjustment to the tree, around an element, that maintains the required ordering of elements CS-2851 Dr. Mark L. Hornick

8 For any right rotation around element x, the right subtree of x’s left child becomes the left subtree of x. CS-2851 Dr. Mark L. Hornick

9 CS-2851 Dr. Mark L. Hornick

10 For any right rotation around element x, the right subtree of x’s left child becomes the left subtree of x. CS-2851 Dr. Mark L. Hornick

11 Exercise: Rotate right about 20 Rule: for any right rotation around element x, the right subtree of x’s left child becomes the left subtree of x. 20 35 10 5 12 7 CS-2851 Dr. Mark L. Hornick

12 Solution: Right rotation about 20
10 35 10 20 5 5 12 35 12 7 7 Note improvement in height CS-2851 Dr. Mark L. Hornick

13 Exercise: Rotate right about 10 Rule: for any right rotation around element x, the right subtree of x’s left child becomes the left subtree of x. 20 35 10 5 12 7 CS-2851 Dr. Mark L. Hornick

14 Solution: Right rotation about 10
20 20 5 35 10 35 10 5 12 12 7 7 Note NO improvement in height CS-2851 Dr. Mark L. Hornick

15 Exercise: Rotate left about 10 Rule: for any left rotation around element x, the left subtree of x’s right child becomes the right subtree of x. 20 35 10 12 5 11 13 7 CS-2851 Dr. Mark L. Hornick

16 Solution: Left rotation about 10
20 20 35 12 10 35 10 13 5 12 5 11 11 13 7 7 Note increase in height CS-2851 Dr. Mark L. Hornick

17 In a rotation around x, the only restructuring is to the subtree rooted at x (nothing above x is affected) CS-2851 Dr. Mark L. Hornick

18 Application of rotations in a certain way maintains the balance of Binary Search Trees
Resulting in AVL trees Red/Black trees others… CS-2851 Dr. Mark L. Hornick

19 Rotations summary CS-2851 Dr. Mark L. Hornick


Download ppt "Balanced Binary Search Trees"

Similar presentations


Ads by Google