iq.lab
Python starts when a code cell comes near or you run one
08 Recursion and trees

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.

About 1 hour 55 minutes, with the 3 problems worked in it
By the end you can
  • 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.

Step throughSearching for 6
Step 1 of 12
Line 1 is about to run.
def search(root, target):
node = root
while node is not None and node.val != target:
if target < node.val:
node = node.left
else:
node = node.right
return node
Names
no names yet
Output
(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.

Work it outA search that misses

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.

nodes

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.

Code itThe closest value at or below

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.

⌘+Enter runsPython starts when a code cell comes near or you run one
Write your code where the starter says 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.

Step throughInserting 7
Step 1 of 22
Line 1 is about to run.
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
root = build_tree([8, 4, 12, 2, 6, 10, 14])
root = insert(root, 7)
Names
no names yet
Output
(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.

PredictSame values, different order

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.

PredictThe tempting check

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.

Step throughThe range each node must fit
Step 1 of 47
Line 1 is about to run.
import math
def show_ranges(node, low, high):
if node is None:
return
print(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)
Names
no names yet
Output
(nothing printed yet)

Work out the ranges for a bigger tree by hand before you write the check.

On paperHand every node its range

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.

ceiling of node 9

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.

mediumBinary search treeTrees, depth-first target 25 min

Is it a binary search tree?

A binary search tree (BST) is a binary tree that keeps one promise at every node: every value in the node's left subtree is smaller than the node's value, and every value in its right subtree is larger. A node's subtree is that node and everything below it. Smaller and larger are strict, so a BST never holds a value twice.

You get the root of a binary tree, which may or may not keep that promise. Return True when every node keeps it, and False when any node breaks it. An empty tree (root is None) counts as a BST: it has no node that breaks the promise.

Trees in the examples are written in level order, the way build_tree reads them: the root, then each row from left to right, with None where a child is missing.

Example 1
Inputroot = [5, 3, 8, 1, 4, None, 9]OutputTrue

Below 5, the left side holds 3, 1 and 4, all smaller than 5, and the right side holds 8 and 9, both larger. The same check passes at 3 and at 8.

Example 2
Inputroot = [5, 3, 8, 1, 6]OutputFalse

6 is the right child of 3, and 6 > 3 is fine there. But 6 is also in the left subtree of 5, where every value must be smaller than 5.

Example 3
Inputroot = [6, 2, 6]OutputFalse

The right child equals the root. Values on the right must be strictly larger.

Constraints
  • 0 ≤ number of nodes ≤ 2 × 105

  • -231 ≤ node value ≤ 231 - 1

  • The tree is at most 600 levels deep, so a recursive solution fits under plain Python's default of about 1,000 nested calls.

Plan it first

Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

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.

PredictInorder on a 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:

  1. Slide left: from the current node, push each node and step to its left child, until you reach None.
  2. Pop the top of the stack. Nothing smaller is left unvisited, so it is the next value in order.
  3. 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.

Step throughInorder with a stack
Step 1 of 62
Line 1 is about to run.
def inorder_print(root):
stack = []
node = root
while stack or node is not None:
while node is not None:
stack.append(node)
node = node.left
node = stack.pop()
print(node.val)
node = node.right
Names
no names yet
Output
(nothing printed yet)

Now put the walk together yourself, collecting the values into a list.

Put in orderInorder with a stack, collected

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.

Your program

Add lines from the list below, in order.

    Unused lines (some do not belong)
    • return values
    • def inorder_values(node):
    • stack.append(node)
    • stack, values = [], []
    • while stack and node is not None:
    • node = node.right
    • while node is not None:
    • node = node.left
    • node = stack.pop()
    • node = node.left
    • while stack or node is not None:
    • values.append(node.val)
    mediumBinary search treeTrees, depth-first target 25 min

    K-th smallest value in a BST

    You get the root of a binary search tree and a number k. In a binary search tree (BST), every value in a node's left subtree (its left child and everything below it) is smaller than the node's value and every value in its right subtree is larger, so no value appears twice.

    Picture the tree's values listed from smallest to largest, and return the one in position k, counting from 1: k = 1 asks for the smallest value.

    Stop as soon as you have the answer. One test asks for small values of k many times on a large tree, and visiting every node on every call is too slow there.

    Trees in the examples are written in level order, the way build_tree reads them: the root, then each row from left to right, with None where a child is missing.

    Example 1
    Inputroot = [5, 3, 7, 2, 4, None, 8], k = 3Output4

    From smallest to largest the values are 2, 3, 4, 5, 7, 8. The third is 4.

    Example 2
    Inputroot = [10, 6, 15, None, 8, 12], k = 4Output12

    From smallest to largest: 6, 8, 10, 12, 15. The fourth is 12, the left child of 15.

    Example 3
    Inputroot = [5, 3, 7, 2, 4, None, 8], k = 6Output8

    The tree has 6 nodes, so k = 6 asks for the largest value.

    Constraints
    • 1 ≤ k ≤ n ≤ 2 × 105, where n is the number of nodes.

    • -109 ≤ node value ≤ 109, all different.

    • The tree is at most 500 levels deep.

    • The function may be called many times on the same tree.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    Step throughWhere 10 and 14 part ways
    Step 1 of 12
    Line 1 is about to run.
    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
    Names
    no names yet
    Output
    (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:

    Quick checkOne comparison too generous

    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.

    mediumBinary search tree target 25 min

    Lowest common ancestor in a BST

    You get the root of a binary search tree and two different nodes of that tree, p and q. In a binary search tree (BST), every value in a node's left subtree (its left child and everything below it) is smaller than the node's value and every value in its right subtree is larger, so no value appears twice.

    An ancestor of a node is any node on the path from the root down to it, the node itself included. The lowest common ancestor of p and q is the deepest node that is an ancestor of both. Return that node: the TreeNode object from the tree, not its value.

    The examples use this tree, written in level order as [20, 10, 30, 5, 15, 25, 35, None, None, 12, 18]. In them, "node 5" means the node holding 5.

             20
           /    \
         10      30
        /  \    /  \
       5   15  25   35
           / \
         12   18
    
    Example 1
    Inputp = node 5, q = node 18Outputnode 10

    5 is in the left subtree of 10 and 18 is in its right subtree, so 10 is the deepest node above both.

    Example 2
    Inputp = node 15, q = node 12Outputnode 15

    12 is the left child of 15, and a node counts as its own ancestor, so the answer is 15 itself.

    Example 3
    Inputp = node 12, q = node 35Outputnode 20

    12 is on the left of the root and 35 is on the right, so the two paths split at the root.

    Constraints
    • 2 ≤ number of nodes ≤ 2 × 105

    • -109 ≤ node value ≤ 109, all different.

    • p and q are different nodes, and both are in the tree.

    • The tree is at most 500 levels deep.

    • The function may be called many times on the same tree.

    Plan it first

    Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.

    ⌘+Enter runs 0:00Python starts when a code cell comes near or you run one
    Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.

    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.

    Say itSay it like 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.

    A few sentences first: 0 of 60 characters.

    Saved in this browser as you type.

    Next: the module checkpoint