Skip to content

Construct Binary Tree from Preorder and Inorder Traversal

Rebuild a tree from two traversals: preorder names each root, inorder splits its two sides.

MediumTree DFS and BST
Solve on LeetCode

The problem

You get two integer arrays, preorder and inorder, which are the preorder and inorder traversals of the same binary tree. Every value in the tree is unique. Rebuild the tree and return its root.

Input preorder = [1, 2, 4, 5, 3, 6], inorder = [4, 2, 5, 1, 3, 6]

Output [1, 2, 3, 4, 5, null, 6]

1 comes first in preorder, so it is the root. In inorder, 4, 2, 5 sit to its left and 3, 6 to its right, and each side splits the same way.

Input preorder = [7, 8, 9], inorder = [9, 8, 7]

Output [7, 8, null, 9]

Inorder puts every value before its root, so each node is the left child of the one before it.

Key constraint: Values are unique, so each value appears exactly once in inorder, and its position there tells you exactly which values are on each side.

How to spot the pattern

  • You get two traversals of the same tree and have to rebuild its shape.
  • One traversal tells you the root (preorder starts with it) and the other tells you which values are left or right of it (inorder).

The idea

The first value of preorder is the root, and its position in inorder splits the remaining values into the left subtree and the right subtree. Preorder lists the whole left subtree before the right one, so if you always build the left side first, the next unused preorder value is the root of whatever subtree you are building. A map from each value to its inorder index makes every split O(1).

Brute force: Find each root in inorder with a linear scan and slice both arrays for every call, which takes O(n^2) time on a skewed tree.

Step by step

  1. 1Build a map from each value to its index in inorder.
  2. 2Keep a pointer to the next unused value in preorder, starting at 0.
  3. 3Write build(lo, hi) for the values in inorder[lo..hi], returning null when lo > hi.
  4. 4Take the next preorder value as the root and look up its inorder index mid.
  5. 5Build the left child from lo..mid - 1 first, then the right child from mid + 1..hi, and return the root.

See the pattern move

The tree dfs and bst pattern on a small example. Step through it, or press play.

Code

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        where = {value: i for i, value in enumerate(inorder)}  # value -> its index in inorder
        next_root = 0  # preorder[next_root] is the root of the next subtree to build

        def build(lo: int, hi: int) -> Optional[TreeNode]:
            # Builds the subtree whose values are inorder[lo..hi].
            nonlocal next_root
            if lo > hi:
                return None
            node = TreeNode(preorder[next_root])
            next_root += 1
            mid = where[node.val]
            node.left = build(lo, mid - 1)  # preorder lists the whole left subtree first
            node.right = build(mid + 1, hi)
            return node

        return build(0, len(inorder) - 1)

Complexity

Time

O(n)

Space

O(n)

Each value becomes one node after one O(1) map lookup; the map holds n entries and the recursion goes as deep as the tree.

Watch out for

  • Building the right subtree before the left: the preorder pointer then hands the left subtree's root to the right side.
  • Scanning inorder with a loop to find every root, which turns O(n) into O(n^2).
  • Off-by-one ranges: the root belongs to neither side, so the sides are lo..mid - 1 and mid + 1..hi.

Follow-up questions

What if you get postorder and inorder instead?

The root is now the last value of postorder. Take values from the end and build the right subtree before the left one.

Can you rebuild a tree from preorder and postorder alone?

Not always: a node with a single child looks the same whether that child is on the left or the right. You need inorder, or a promise that every node has 0 or 2 children.

In Hinglish

Preorder ka pehla number root hai, aur inorder mein uski position batati hai ki kaun left mein hai aur kaun right mein. Pehle left subtree banao, phir right, aur position ke liye map rakho.

Related problems