Download presentation

Presentation is loading. Please wait.

Published byAlyson Gunnin Modified over 2 years ago

1
Binary Tree Structure a b fe c a rightleft g g NIL c ef b left right pp p pp left key

2
Inorder Traversal 1. Traverse the left subtree. 2. Visit the node. 3. Traverse the right subtree. a b c d e Traversal order: bdaec (n) Running time: T(n) = T(k) + T(n–k – 1) + d visit time d size k size n–k–1 c b a d e

3
Postorder Traversal 1. Traverse the left subtree. 2. Traverse the right subtree. 3. Visit the node. a b c d e Traversal order: dbeca c e a b d

4
Preorder Traversal 1. Visit the node. 2. Traverse the left subtree. 3. Traverse the right subtree. a b c d e Traversal order: abdce e c d b a

5
Another Traversal Example Preorder: Inorder: Postorder: 15, 6, 3, 2, 4, 7, 13, 9, 18, 17, 20 2, 3, 4, 6, 7, 9, 13, 15, 17, 18, 20 2, 4, 3, 9, 13, 7, 6, 17, 20, 18, 15

6
Binary Search Trees Storage of elements for efficient access. The binary-search-tree property: If node y in left subtree of node x, then key[y] < key[x]. Supporting dynamic set operations. If node y in right subtree of node x, then key[y] key[x].

7
A BST Example Search for 37 Search time O(h) where h is tree height

8
Inorder Traversal of BST Prints out keys in sorted order: 10, 20, 25, 30, 31, 35, 37, 50, 53, 55, 60, 62

9
Successor and Predecessor The predecessor of x is the rightmost node in its left subtree: The successor of x is the leftmost node in its right subtree x 10, 20, 25, 30, 31, 35, 37, 50, 53, 55, 60, y The successor of y is lowest ancestor whose left child is y or an ancestor of y no right subtree

10
BST Operations Preview Insert 8 Delete The successor of

11
Insertion Example: insert z = x Compare 32 and 25 traverse the right subtree Compare 32 and 35, traverse the left subtree insert 32 as left child x y y z

12
Deletion (A) Case A: node x (to be deleted) is a leaf node Operation: update the parent node to have an empty subtree x

13
Deletion (B) Case B: node x has a left child but no right child Operation: attach the left subtree of x to the parent x 17

14
Deletion (C) Case C: node x has a right child but no left child Operation: attach the right subtree of x to the parent x

15
Deletion (D) Case D: node x has two children r x A C D y z B 2. Unlink y from the tree. 3. Connect ys right subtree to its parent. 4. Finally, connect y at the deleted node. r x A C D y z B Operation: 1. Select as the replacement (of x) node y, the successor of x. y has the smallest value greater than that of x. y

16
Deletion (D) - an Example replacement of , 25, 28, 30, 33, 34, 35, 40, 50, 6510, 25, 28, 33, 34, 35, 40, 50, 65

17
Running Time All basic operations on a binary search tree of height h run in O(h) time. Main question: How to guarantee h = O(lg n)? One answer: red-black trees! n2n … Insert 4 Insert 6 A worst case :

Similar presentations

© 2017 SlidePlayer.com Inc.

All rights reserved.

Ads by Google