Binary Tree Structure a b fe c a rightleft g g NIL c ef b left right pp p pp left key
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
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
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
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
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].
A BST Example Search for 37 Search time O(h) where h is tree height
Inorder Traversal of BST Prints out keys in sorted order: 10, 20, 25, 30, 31, 35, 37, 50, 53, 55, 60, 62
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
BST Operations Preview Insert 8 Delete The successor of
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
Deletion (A) Case A: node x (to be deleted) is a leaf node Operation: update the parent node to have an empty subtree x
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
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
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
Deletion (D) - an Example replacement of , 25, 28, 30, 33, 34, 35, 40, 50, 6510, 25, 28, 33, 34, 35, 40, 50, 65
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 :