Lesson 5 of 5
Binary search trees
A binary search tree keeps one promise at every node, smaller values on the left and larger values on the right. That promise lets search and insert walk a single path, makes an inorder walk come out sorted, and turns three classic interview questions into short walks.
Search and insert in a BST by walking one path, and say why the cost is O(h)
Explain why sorted input builds a tall tree, and what that does to the cost
Check whether a tree is a BST by handing every node the range its ancestors allow
Walk a BST inorder with a stack, and stop at the k-th smallest value
Find the lowest common ancestor in a BST by walking down until two values part ways
Binary search finds a value in a sorted list of a million numbers by looking at no more than 20 of them. Now add one new value. The list must stay sorted, so every item after the new value's spot shifts one slot to the right: up to a million moves for a single insert.
A binary search tree keeps sorted values in linked nodes instead of a row of slots. Finding a value walks one path down from the top. Adding a value walks the same path and hangs a new node at the bottom. Nothing shifts.
One promise makes all of this work, and the same promise answers three classic interview questions: is this tree a BST, what is its k-th smallest value, and where do two nodes meet. This lesson builds the promise, then uses it each way.
The promise, and a search that uses it
A reminder from the binary trees lesson: a tree node holds a value val and two links, left and right, each pointing at a child node or at None. A node's subtree is that node and everything below it. Its left subtree is the subtree of its left child, and its right subtree the subtree of its right child. build_tree reads a list level by level, each level left to right, with None for a missing child.
A binary search tree (BST) is a binary tree that keeps one promise at every node:
Here is the tree this lesson uses most, built with build_tree([8, 4, 12, 2, 6, 10, 14]):
8
/ \
4 12
/ \ / \
2 6 10 14
Check the promise at the top. The left subtree of 8 holds 4, 2 and 6, all smaller than 8. The right subtree holds 12, 10 and 14, all larger. It holds at 4 and at 12 too. The promise is about whole subtrees, not only children. And because "smaller" and "larger" are strict, a BST holds each value at most once.
Search uses the promise to rule out a whole subtree with every comparison. Is 6 in the tree? Compare it with the top, 8. 6 is smaller, and everything on the right of 8 is larger than 8, so 6 cannot be there. Move left to 4 and ask again. Before you step through, guess how many nodes the search looks at.
def search(root, target):node = rootwhile node is not None and node.val != target:if target < node.val:node = node.leftelse:node = node.rightreturn node
(nothing printed yet)Each comparison throws away the node and one whole subtree, so the search meets at most one node per level.
The height decides the cost. Our tree has 3 levels, so any search looks at no more than 3 nodes. A tree of a million values with every level full (except perhaps the bottom one) has 20 levels, so a search there looks at no more than 20 nodes, the same as binary search on the sorted list.
Trace search from above by hand on the same tree, [8, 4, 12, 2, 6, 10, 14], but look for 11, which is not in the tree. How many nodes does it compare with 11 before it falls off the tree? Type a whole number.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
A search that misses still learns something on the way down. Every node it passed with a value below the target is a candidate for "the closest value at or below the target". Interviewers often change a familiar problem rather than repeat it word for word (the research digest calls this deforming it), so practice one such change now: same walk, one more name in the notebook.
Write closest_below(root, x): return the largest value in the BST that is at most x, or None if every value is larger than x (an empty tree has no values). In [8, 4, 12, 2, 6, 10, 14], closest_below(root, 11) is 10 and closest_below(root, 1) is None.
Walk one path, the way search does, and keep one extra name: the best candidate so far. Then press Watch it run.
raise NotImplementedError, then press Run tests. Each check says what it expects.To recap: the promise holds at every node, and a search walks one path of at most h nodes. A search for a missing value ends at an empty spot, and that spot turns out to be useful.
Insert: search until you fall off
Where would 7 go in our tree? Search for it: 7 < 8, go left. 7 > 4, go right. 7 > 6, go right, and the right child of 6 is None. The empty spot where a failed search ends is exactly where the new value belongs. Hanging 7 there keeps the promise at 8, 4 and 6, the only nodes it sits below.
Here is insert as a recursive function. insert(node, val) puts val into the subtree under node and returns the top node of that subtree. Before you step through, guess how many insert calls are open at the moment the new node is made.
def insert(node, val):if node is None:return TreeNode(val)if val < node.val:node.left = insert(node.left, val)else:node.right = insert(node.right, val)return noderoot = build_tree([8, 4, 12, 2, 6, 10, 14])root = insert(root, 7)
(nothing printed yet)Every call hands back the top of its subtree, and its caller hooks that back on. Only the call that reaches an empty spot hands back something new. That is what makes an empty tree work too: insert(None, 7) returns the new node, and root = insert(root, 7) makes it the root.
This insert assumes val is not in the tree yet. Inserting 6 a second time would take the else at every node from 4 down, and hang a second 6 as the right child of the first, breaking the strict promise. To keep each value once, return node unchanged when val == node.val.
Insert walks the same path as search, so it costs O(h) time. The recursive version also keeps one call per level on the stack: O(h) space. But what is h? That depends on the order the values arrive in.
insert is the function from the trace. height counts the levels of a tree (the max depth from the binary trees lesson). The same seven values go into two empty trees, in two different orders. Type exactly what this prints.
def insert(node, val):
if node is None:
return TreeNode(val)
if val < node.val:
node.left = insert(node.left, val)
else:
node.right = insert(node.right, val)
return node
def height(node):
if node is None:
return 0
return 1 + max(height(node.left), height(node.right))
for order in [[4, 2, 6, 1, 3, 5, 7], [1, 2, 3, 4, 5, 6, 7]]:
root = None
for v in order:
root = insert(root, v)
print(height(root))
Sorted input builds a path: a chain in which every node has one child, except the last. Each new value is larger than everything already in the tree, so it goes right at every node and lands at the bottom. After 1 to 7 in order, the tree is one long line of 7 levels, and a search for 7 compares with every node: no better than scanning a list.
Self-balancing trees (red-black trees and AVL trees are the common ones) fix this by reshaping themselves after every insert and delete, so h stays O(log n). Python's standard library has no BST of any kind; in the problems here, the tree is handed to you as its root node. Height also limits recursion: a recursive walk down a path of 100,000 nodes needs 100,000 nested calls, and plain Python stops at about 1,000 by default (this lab allows 5,000). A loop has no such limit. search is already one, and insert can be one too: walk down as search does, then hang the new node on the last node passed.
To recap: search and insert both walk one path, so both cost O(h). h runs from about log₂ n for a balanced tree to n for a path, and the order the values arrive in decides which you get.
Checking the promise: ranges come down from above
Is a given tree a BST? That is LeetCode 98. The tempting answer checks each node against its two children: the left child smaller, the right child larger. Predict what that check says about two trees.
This check compares every node with its two children only. Here are the two trees it gets, drawn from their level order:
5 5
/ \ / \
3 8 3 8
/ \ / \
1 6 4 1
Type exactly what the program prints.
def looks_like_bst(node):
if node is None:
return True
if node.left is not None and node.left.val >= node.val:
return False
if node.right is not None and node.right.val <= node.val:
return False
return looks_like_bst(node.left) and looks_like_bst(node.right)
print(looks_like_bst(build_tree([5, 3, 8, 1, 6])))
print(looks_like_bst(build_tree([5, 3, 8, 4, 1])))
The 6 is the problem. It is the right child of 3, and 6 > 3 is fine there. But 6 is also inside the left subtree of 5, and the promise at 5 says everything there is smaller than 5. An ancestor of a node, as in the lesson on passing answers up, is a node on the path from the root down to it. A node must keep the rule of every ancestor above it, not only its parent.
Every ancestor above a node sets one limit. When the path from the root goes left at a node with value a, everything below must be smaller than a: a ceiling. When it goes right at value b, everything below must be larger than b: a floor. Only the tightest limits matter, the highest floor and the lowest ceiling, so each node gets one range, low < val < high, handed down by its parent. The left child gets (low, val): a node that fits has val below high, so val is the tighter ceiling. The right child gets (val, high) the same way. Nothing is above the root, so it starts with -math.inf and math.inf, which are below and above every number.
This walk prints the range each node gets, on the first tree from the exercise above. Before you step through, guess which node gets a range its value does not fit.
import mathdef show_ranges(node, low, high):if node is None:returnprint(low, "<", node.val, "<", high)show_ranges(node.left, low, node.val)show_ranges(node.right, node.val, high)show_ranges(build_tree([5, 3, 8, 1, 6]), -math.inf, math.inf)
(nothing printed yet)Work out the ranges for a bigger tree by hand before you write the check.
On paper, copy this tree, [10, 5, 15, 2, 8, 12, 20, None, None, 6, 9], and write next to every node the range (low, high) that show_ranges would hand it:
10
/ \
5 15
/ \ / \
2 8 12 20
/ \
6 9
Then type the ceiling (the high) of node 9.
Work it on real paper: writing each step is the point. Then check your final answer here and compare your working with the walk-through.
Type a number: 12, -1, 0.5 and 3/4 all work. Enter checks.
Now turn the walk into a check. Instead of printing, return False the moment a value falls outside its range, and True for an empty subtree.
Three changes turn show_ranges into the answer: an empty subtree returns True, a value outside its range returns False, and the two recursive calls are joined with and, so the first failure ends the walk. Starting with the infinities matters as well: a starting ceiling of 2**31 - 1 would reject a node that holds exactly that value.
Inorder walks the values in sorted order
Read the drawing of our tree from left to right: 2, 4, 6, 8, 10, 12, 14. The values come out sorted. The walk that visits a tree in that order is the inorder walk from the binary trees lesson: the left subtree, then the node, then the right subtree. Predict what it prints for a different BST.
This is the recursive inorder walk: everything in the left subtree, then the node, then everything in the right subtree. Type exactly what it prints for the BST [6, 2, 9, 1, 4, 8], one value per line.
def inorder(node):
if node is None:
return
inorder(node.left)
print(node.val)
inorder(node.right)
inorder(build_tree([6, 2, 9, 1, 4, 8]))
Why it always comes out sorted: inorder lists a subtree as its left subtree's values, then the node, then its right subtree's values. The promise says everything on the left is smaller than the node and everything on the right is larger. So if the lists for the two child subtrees are sorted, the whole list is sorted. An empty subtree gives an empty list, which is sorted, so the argument climbs from the bottom to the whole tree.
So the k-th smallest value is the k-th node an inorder walk meets (LeetCode 230). Walking the whole tree into a list works, but it costs O(n) even when k is 1. Better: count as you go, and stop at the k-th node. A recursive walk can stop early only by passing a "found it" signal back up through every open call. So we walk inorder with a loop and a list used as a stack (last in, first out), as the binary trees lesson did for preorder, and one return stops it. The walk has three moves:
- Slide left: from the current node, push each node and step to its left child, until you reach
None. - Pop the top of the stack. Nothing smaller is left unvisited, so it is the next value in order.
- Turn right: move to the popped node's right child, and slide left again from there.
This trace prints every value, so you can watch the whole walk. The stack is drawn with its top at the top. Before you step through, guess the most nodes the stack ever holds at once.
def inorder_print(root):stack = []node = rootwhile stack or node is not None:while node is not None:stack.append(node)node = node.leftnode = stack.pop()print(node.val)node = node.right
(nothing printed yet)Now put the walk together yourself, collecting the values into a list.
Put the lines in order to build inorder_values(node), which returns the values of a BST from smallest to largest with the stack walk from the trace: slide left, pop, turn right. Indentation is part of each line. Two of the lines do not belong.
Add lines from the list below, in order.
return valuesdef inorder_values(node):stack.append(node)stack, values = [], []while stack and node is not None:node = node.rightwhile node is not None:node = node.leftnode = stack.pop()node = node.leftwhile stack or node is not None:values.append(node.val)
The only new piece is the counter: add one at each pop, and return the value when the count reaches k. The walk stops at the k-th pop, so it pushes at most k + h nodes however big the tree is, and that is what the speed test checks.
Where two searches part ways
The lesson on passing answers up found the lowest common ancestor (LCA) of two nodes: the deepest node that is an ancestor of both, where a node counts as its own ancestor. In an ordinary binary tree that walk had to look through both subtrees, which costs O(n). In a BST, the values tell you which side each node is on.
Picture two searches starting together at the root, one for each value. While both values are smaller than the node, both searches go left. While both are larger, both go right. The first node where the two searches would go different ways, or where one of them finds its value, is the LCA (LeetCode 235).
The code loops with while True:, which has no stopping test of its own: it repeats until a return (or break) inside it runs, so check that the loop is sure to reach one. Here the else returns at the latest on the node that holds a or b, as long as both values are in the tree. The trace runs it on 10 and 14 in our tree. Before you step through, find on the drawing the node where their searches part.
def split_point(root, a, b):node = rootwhile True:if a < node.val and b < node.val:node = node.leftelif a > node.val and b > node.val:node = node.rightelse:return node.val
(nothing printed yet)split_point trusts that both values are in the tree. With 1 and 0, both smaller than every node, it walks left past 2 onto None, and node.val raises an error. With 10 and 11, it returns 10, though the tree holds no 11.
The test for "same side" must be strict. Here is what one wrong comparison does:
This version of split_point uses <= in the first test instead of <:
def split_point(root, a, b):
node = root
while True:
if a <= node.val and b <= node.val:
node = node.left
elif a > node.val and b > node.val:
node = node.right
else:
return node.val
With root = build_tree([8, 4, 12, 2, 6, 10, 14]), our usual tree, what does split_point(root, 4, 2) return?
Choose one answer, then check.
In the problem, you get the two nodes themselves, p and q, and you return a node, not a value.
The walk is split_point with nodes: compare p.val and q.val with node.val, and return node. When p sits above q, the walk stops at p, because a node is its own ancestor.
Last, say the validation answer the way you would in the room.
An interviewer asks you to check whether a binary tree is a valid BST. Before typing, say why comparing each node with its children is not enough (with a small example), then give the walk, the notebook, the promise and the cost of your approach.
Saved in this browser as you type.