Final challenge: validate, kth smallest, common ancestor
After this: Check that a tree is a BST, and find the kth smallest key and a lowest common ancestor.
This challenge has three steps, and each step is scored on its own.
- Validate. Four trees look like binary search trees. Find the one that really is.
- Kth smallest. Predict the kth smallest key. For example, k = 3 means the third smallest.
- Lowest common ancestor. An ancestor of a key is any node on the path from the root down to it. The lowest common ancestor of two keys is the deepest node that is on both paths.
Steps 2 and 3 use the example tree after two changes: 45 is inserted, then 30 is deleted. The keys are now 20, 40, 45, 50, 60, 70, 80. The root is 50. On its left is 40, with children 20 and 45. On its right is 70, with children 60 and 80.
You can try as many times as you like, and hints work as they do in the lessons.
Step 1 of 3Validate a BST
Validate a BST
Here are four trees. A check that only compares each node with its two children accepts three of them. The code below is stricter: it passes down the limits, or bounds, that each key must stay between. Which tree does it accept, making it the only real binary search tree?
def is_bst(node, lo=None, hi=None): """Every key must sit strictly between the bounds its ancestors set.""" if node is None: return True if lo is not None and node.key <= lo: return False if hi is not None and node.key >= hi: return False return is_bst(node.left, lo, node.key) and is_bst(node.right, node.key, hi)/** Every key must sit strictly between the bounds its ancestors set. */static boolean isBst(Node node, Integer lo, Integer hi) { if (node == null) return true; if (lo != null && node.key <= lo) return false; if (hi != null && node.key >= hi) return false; return isBst(node.left, lo, node.key) && isBst(node.right, node.key, hi);}Kth smallest
The tree holds 50, 30, 70, 20, 40, 60, 80. Then 45 is inserted and 30 is deleted. What does the last line print?
def kth_smallest(root, k): """The k-th key in inorder (k = 1 is the smallest), stopping as soon as it is reached.""" stack, node = [], root while stack or node is not None: while node is not None: # as far left as possible, remembering the way back stack.append(node) node = node.left node = stack.pop() # the next key in order k -= 1 if k == 0: return node.key node = node.right return None
t = BST()for k in [50, 30, 70, 20, 40, 60, 80]: t.insert(k)t.insert(45)t.delete(30)print(kth_smallest(t.root, 3), kth_smallest(t.root, 6))/** The k-th key in inorder (k = 1 is the smallest), stopping as soon as it is reached. */static Integer kthSmallest(Node root, int k) { Deque<Node> stack = new ArrayDeque<>(); Node node = root; while (!stack.isEmpty() || node != null) { while (node != null) { // as far left as possible, remembering the way back stack.push(node); node = node.left; } node = stack.pop(); // the next key in order k -= 1; if (k == 0) return node.key; node = node.right; } return null;}
BST t = new BST();for (int k : new int[] {50, 30, 70, 20, 40, 60, 80}) t.insert(k);t.insert(45);t.delete(30);System.out.println(kthSmallest(t.root, 3) + " " + kthSmallest(t.root, 6));Lowest common ancestor
This is the same tree: root 50, with 40 on the left (children 20 and 45) and 70 on the right (children 60 and 80). What is the lowest common ancestor of 45 and 60?
def lca(root, a, b): """The lowest node with both a and b in its subtree (both keys are in the tree).""" node = root while node is not None: if a < node.key and b < node.key: node = node.left # both on the left: the answer is down there elif a > node.key and b > node.key: node = node.right # both on the right else: return node.key # they part ways here, or one of them is this node return None/** The lowest node with both a and b in its subtree (both keys are in the tree). */static Integer lca(Node root, int a, int b) { Node node = root; while (node != null) { if (a < node.key && b < node.key) node = node.left; // both on the left: the answer is down there else if (a > node.key && b > node.key) node = node.right; // both on the right else return node.key; // they part ways here, or one of them is this node } return null;}- Check that a tree is a BST by passing limits down from the root, find the kth smallest key with an inorder walk that stops early, and find a lowest common ancestor with the order rule.