← Whiteboard questions

Construct Binary Tree from Preorder and Inorder

Rebuild a tree from its preorder and inorder lists

DSA, Medium, Trees

Which structure or algorithm, and what does it cost.

A tree has distinct values. The list preorder gives its values as the root, then the whole left subtree, then the whole right subtree. The list inorder gives the whole left subtree, then the root, then the whole right subtree. Both lists come from the same tree. Return the root of the tree (each node has val, left and right, null when missing), or the tree as a level-order list without trailing nulls; either is fine. The examples show the level-order list: values row by row, left to right, with null for a missing child. Two empty lists give an empty tree.

Examples

Input preorder = [7, 3, 1, 5, 9, 8], inorder = [1, 3, 5, 7, 8, 9]
Output [7, 3, 9, 1, 5, 8]
Why the root is 7. In the inorder list, 1, 3, 5 lie left of 7 and 8, 9 lie right of it.
Input preorder = [4, 5, 6], inorder = [6, 5, 4]
Output [4, 5, null, 6]
Why every value lies left of its parent, so the tree is a chain leaning left.
Input preorder = [], inorder = []
Output []
Why two empty lists give an empty tree.

Constraints

Your answer must contain

Target Aim for O(n) time.

Hints

Try the problem first. Open one hint at a time.

Hint 1 a nudge

One of the two lists always shows you the root first. Which one, and what does the other list tell you about it?

Hint 2 the approach

Find the root in the inorder list. What do the values on each side of it have in common?

Hint 3 the key step

Save each value's inorder position. A node's left part size shows where its right child sits in the preorder list. Build both children from ranges.

Walkthrough

Full walkthrough brute force to best

Brute force

Take the first preorder value as the root. Search for it in the inorder list, cut both lists into a left part and a right part, and repeat on each part. The search costs O(n) at every node, and cutting the lists copies them. On a chain this is O(n^2) time.

Best method

The first value of a preorder range is its root. In the inorder list, the values left of that root form the left subtree and the values right of it form the right subtree. If the left part has s values, then the preorder range after the root starts with those s values for the left subtree, and the right subtree follows. So no copy is needed: a subtree is just a preorder start position and an inorder range. Save the inorder position of every value in a table once, so finding a root is one lookup. Use a stack of such subtrees, so a long chain cannot overflow the call stack. Each value is placed once, so the work is linear.

Hand trace

Run on preorder = [7, 3, 1, 5, 9, 8] and inorder = [1, 3, 5, 7, 8, 9]. The inorder positions are 1: 0, 3: 1, 5: 2, 7: 3, 8: 4, 9: 5. The root is 7, at inorder position 3. The left part has 3 values, so its root is preorder[1] = 3. The right part starts after those 3 values, so its root is preorder[4] = 9. Node 9 sits at position 5. Its left part is position 4 only, so its left child is preorder[5] = 8. Node 3 is at position 1: its left part is position 0, with root preorder[2] = 1, and its right part is position 2, with root preorder[3] = 5. Reading by rows gives [7, 3, 9, 1, 5, 8].

Code

class Node:
    def __init__(self, val):
        self.val = val
        self.left = self.right = None
def build_from_walks(preorder, inorder):
    if not preorder:
        return None
    where = {v: i for i, v in enumerate(inorder)}
    root = Node(preorder[0])
    stack = [(root, 0, 0, len(inorder) - 1)]
    while stack:
        node, p, lo, hi = stack.pop()
        mid = where[node.val]
        if mid > lo:
            node.left = Node(preorder[p + 1])
            stack.append((node.left, p + 1, lo, mid - 1))
        if mid < hi:
            node.right = Node(preorder[p + 1 + mid - lo])
            stack.append((node.right, p + 1 + mid - lo, mid + 1, hi))
    return root

Time and memory

O(n) time, because the table costs O(n) and each value is placed once with one lookup. O(n) memory for the table and the stack.

Common mistakes

  • Taking the right subtree to start right after the root in the preorder list. The left subtree comes first, so skip its size.
  • Searching the inorder list again for every root. Save the positions once, or the work becomes O(n^2).
  • Slicing the lists at every node. Each slice copies values, so a chain costs O(n^2). Pass index ranges instead.

Related problems

More Trees problems
Construct Binary Tree from Preorder and Inorder walkthrough