Skip to main content
33

Construct Binary Tree from Preorder and Inorder Traversal

Mediumtreesrecursion

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:TreesRead the beginner guide

You're given two arrays describing the same binary tree, whose values are all unique:

  • preorder: the values in preorder (node, then left subtree, then right subtree).
  • inorder: the values in inorder (left subtree, then node, then right subtree).

Rebuild the tree and return its root.

Understand the problem

A traversal is an order for visiting every node of a tree. These two differ only in when the node itself is written down:

TraversalOrderFor the tree below
preordernode, left subtree, right subtree3, 9, 20, 15, 7
inorderleft subtree, node, right subtree9, 3, 15, 20, 7
text
    3
   / \
  9  20
    /  \
   15   7

Neither list alone is enough to know the tree's shape. Together they are: your job is to work the shape back out.

Example 1

text
Input:  preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7]
Output: [3, 9, 20, null, null, 15, 7]

The tree drawn above.

Example 2

text
Input:  preorder = [-1], inorder = [-1]
Output: [-1]

A single node.

How trees are written in the tests: level by level, top to bottom, left to right, with null for a missing child.

Constraints

  • 1 <= preorder.length <= 3000
  • inorder.length == preorder.length
  • All values are unique, and both arrays describe the same tree.

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    The first preorder value is the root; finding it in inorder tells you which values are in the left subtree and which are in the right, so you build each side the same way, recursively.

    The key insight

    Each traversal gives you one piece of information:

    • Preorder (node, left, right) always lists the root first. So preorder[0] is the root.
    • Inorder (left, node, right) has the root in the middle: everything before it belongs to the left subtree, everything after it to the right subtree.
    text
    preorder = [3,  9,  20, 15, 7]     → the root is 3
    inorder  = [9,  3,  15, 20, 7]
                ↑   ↑   ─────────
              left root   right

    So the left subtree is {9} and the right subtree is {15, 20, 7}. Each of those is the same problem, just smaller: recursion.

    Making it fast

    Two small tricks avoid copying arrays at every step:

    1. A map from value to its index in inorder, built once. Finding where the root sits becomes instant.
    2. One pointer into preorder. Preorder lists nodes in exactly the order the recursion creates them (node, then all of its left subtree, then all of its right subtree), as long as we build the left side before the right side. So the next root is always simply "the next preorder value".

    build(lo, hi) builds the subtree made of inorder[lo..hi]:

    1. If lo > hi, the range is empty: return null.
    2. Take the next preorder value as the root, and find its index mid in inorder.
    3. Left subtree = build(lo, mid - 1), then right subtree = build(mid + 1, hi).

    Step by step

    preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7] (indexes 0 to 4):

    CallNext preorder valueIts inorder indexBuilds
    build(0, 4)31root 3; left = build(0, 0), right = build(2, 4)
    build(0, 0)909; both sides empty
    build(2, 4)20320; left = build(2, 2), right = build(4, 4)
    build(2, 2)15215; both sides empty
    build(4, 4)747; both sides empty

    Notice the preorder values are used in order, 3, 9, 20, 15, 7, one per call.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(n). Each node is created once, and each lookup in the map is O(1).
    • Memory: O(n) for the map, plus O(h) for the recursion.

    Common mistakes

    • Building the right subtree before the left. The preorder pointer then hands out the wrong values. Left first, always.
    • Slicing arrays in every call. It works, but copies data at every level: O(n²) in the worst case.
    • Searching inorder with indexOf every time. Also O(n) per node. Build the map once.

    Going deeper

    • This only works because the values are unique. With duplicates, you couldn't tell which 3 in inorder is the root.
    • The same idea rebuilds a tree from postorder + inorder: in postorder the root is last, so you read postorder backward and build the right side first.

    Reference solution

    js
    /**
     * @param {number[]} preorder
     * @param {number[]} inorder
     * @return {TreeNode | null}
     */
    export default function buildTree(preorder, inorder) {
      // Where each value sits in inorder, so we can find a root's position instantly.
      const indexOf = new Map(inorder.map((value, i) => [value, i]))
      // Preorder lists the roots in exactly the order we build them (node, left, right).
      let next = 0
    
      // Build the subtree made of the values inorder[lo..hi].
      function build(lo, hi) {
        if (lo > hi) return null // empty range: no subtree here
        const value = preorder[next++] // the next preorder value is this subtree's root
        const mid = indexOf.get(value)
        const node = new TreeNode(value)
        // Values left of the root in inorder form the left subtree, values right of it the right.
        // Build LEFT first: that's the order preorder lists them in.
        node.left = build(lo, mid - 1)
        node.right = build(mid + 1, hi)
        return node
      }
    
      return build(0, inorder.length - 1)
    }
    ts
    export default function buildTree(preorder: number[], inorder: number[]): TreeNode | null {
      // Where each value sits in inorder, so we can find a root's position instantly.
      const indexOf = new Map(inorder.map((value, i) => [value, i]))
      // Preorder lists the roots in exactly the order we build them (node, left, right).
      let next = 0
    
      // Build the subtree made of the values inorder[lo..hi].
      function build(lo: number, hi: number): TreeNode | null {
        if (lo > hi) return null // empty range: no subtree here
        const value = preorder[next++] // the next preorder value is this subtree's root
        const mid = indexOf.get(value)!
        const node = new TreeNode(value)
        // Values left of the root in inorder form the left subtree, values right of it the right.
        // Build LEFT first: that's the order preorder lists them in.
        node.left = build(lo, mid - 1)
        node.right = build(mid + 1, hi)
        return node
      }
    
      return build(0, inorder.length - 1)
    }
    python
    def build_tree(preorder: list[int], inorder: list[int]) -> TreeNode | None:
        # Where each value sits in inorder, so we can find a root's position instantly.
        index_of = {value: i for i, value in enumerate(inorder)}
        # Preorder lists the roots in exactly the order we build them (node, left, right).
        next_index = 0
    
        # Build the subtree made of the values inorder[lo..hi].
        def build(lo: int, hi: int) -> TreeNode | None:
            nonlocal next_index
            if lo > hi:
                return None  # empty range: no subtree here
            value = preorder[next_index]  # the next preorder value is this subtree's root
            next_index += 1
            mid = index_of[value]
            node = TreeNode(value)
            # Values left of the root in inorder form the left subtree, values right of it the right.
            # Build LEFT first: that's the order preorder lists them in.
            node.left = build(lo, mid - 1)
            node.right = build(mid + 1, hi)
            return node
    
        return build(0, len(inorder) - 1)