Binary Search Tree (BST) 15 < > 7 17 3 9 19 What is the 1 4 8 11 inorder traversal of a BST? 23
BST Definition BST is a binary tree Each node stores a value from an ordered domain, e.g., numbers or strings The value of any node is ≥ all values in the left subtree, and ≤ all values in the right subtree 24
BST ADT Initialize() – Initializes an empty BST Find(x) – Searches for x in the tree and returns true or false Insert(x) – Inserts the value x into the BST Delete(x) – Deletes the value x from the tree if it is in the tree FindMin() – Returns the minimum value in the tree without deleting it FindMax() – Returns the maximum value in the tree without deleting it 25
BST.Find Find 8 15 Find 14 7 17 3 9 19 1 4 8 11 26
BST.Find bool find(Node* node, T x) { if (node == null) return false ; if (x == node.value) return true ; if (x < node.value) find(node.____, x); if (x > node.value) find(node.____, x); } 27
BST.Find bool find(Node* node, T x) { if (node == null) return false ; if (x == node.value) return true ; if (x < node.value) find(node.left, x); if (x > node.value) find(node.right, x); FindMin() } FindMax() 28
BST.Insert Insert 18 15 7 17 3 9 19 1 4 8 11 18 29
BST.Insert Insert 14 15 7 17 3 9 19 1 4 8 11 18 14 30
BST.Remove Remove 11 15 7 17 3 9 19 1 4 8 11 31
BST.Remove Remove 9 15 7 17 3 9 19 1 4 8 32
BST.Remove Remove 7 15 7 17 3 9 19 1 4 8 11 33
BST.Remove Remove 7 15 17 3 9 19 1 4 8 11 34
BST.Remove Remove 7 15 17 3 9 19 1 4 8 11 35
BST.Remove Remove 7 15 8 17 3 9 19 1 4 11 36
BST.Remove Remove 7 15 8 17 3 9 19 1 4 11 37
Analysis of BST Algorithms Operations: Find Insert FindMin FindMax Delete All O(h) where h is the height of the tree h = O(n) (worst case) h = Ω (log n) (best case) How to guarantee O(log n) performance? 38
Recommend
More recommend