Construct Binary Tree from Preorder and Inorder Traversal

MediumTree recursionLeetCode 105 ↗World 3-15
0:00 / 0:00

Rebuild a tree from two traversals. Preorder names each root; its spot in inorder splits the left and right subtrees.

▼

The problem

LeetCode 105 (Medium). Given the preorder and inorder traversals of a binary tree with distinct values, rebuild the tree and return its root.

Example: preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7] → the tree [3, 9, 20, null, null, 15, 7] (3 at the root, 9 on its left, 20 on its right, 15 and 7 under 20).

def buildTree(preorder, inorder):
    where = {v: i for i, v in enumerate(inorder)}
    nxt = 0
    def build(lo, hi):
        nonlocal nxt
        if lo > hi:
            return None
        root = TreeNode(preorder[nxt])
        nxt += 1
        mid = where[root.val]
        root.left = build(lo, mid - 1)
        root.right = build(mid + 1, hi)
        return root
    return build(0, len(inorder) - 1)
TRY IT ON LEETCODE ▶

The solution

def buildTree(preorder, inorder):
    where = {v: i for i, v in enumerate(inorder)}
    nxt = 0
    def build(lo, hi):
        nonlocal nxt
        if lo > hi:
            return None
        root = TreeNode(preorder[nxt])
        nxt += 1
        mid = where[root.val]
        root.left = build(lo, mid - 1)
        root.right = build(mid + 1, hi)
        return root
    return build(0, len(inorder) - 1)

Transcript

Construct Binary Tree from Preorder and Inorder Traversal. You get two lists from the same tree. Preorder visits the root, then the left subtree, then the right. Inorder visits the left subtree, then the root, then the right. From the two lists, rebuild the tree.

Preorder is three, nine, twenty, fifteen, seven. Inorder is nine, three, fifteen, twenty, seven. Together they make one tree: three on top, nine on its left, twenty on its right, fifteen and seven under twenty. Each node stands right above its spot in inorder.

The simple way: first in preorder, three, is the root. Scan inorder to find it. What's before it is the left subtree, what's after is the right. Repeat on each side. But on a lopsided tree, every scan walks its whole range: fifteen checks for five values, order n squared.

The fix: map each value to its inorder position, once. Now finding a root is one lookup. And if we always build the left side before the right, the next preorder value is always the next root.

In code, build the map and a pointer into preorder. The helper builds the tree for an inorder range, low to high. An empty range means no node. Otherwise, take the next preorder value, look up where it splits the range, then build the left side, then the right.

Let's run it. Three comes first: the root, at position one. Nine goes left; fifteen, twenty and seven go right. Next is nine, alone in its range: both sides are empty, so it's a leaf. Next, twenty, at position three. Fifteen goes left, seven goes right. The tree is rebuilt.

Each value is placed once, with one lookup, so the time is order n. The map holds n entries, and the recursion can go n deep, so the space is order n too.

Preorder picks the root, inorder splits the sides. That's Construct Binary Tree from Preorder and Inorder Traversal.