Construct Binary Tree from Preorder and Inorder Traversal (LeetCode 105): Solution and Explanation

Medium
Array
Hash Table
Divide And Conquer
Tree
Binary Tree

You are given two arrays describing the same binary tree: its preorder traversal and its inorder traversal. All values are unique. Rebuild the original tree and return its root.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

Each traversal alone is ambiguous, since many trees share the same preorder or the same inorder sequence. The question is what each one tells you that the other does not. Preorder always lists a node before anything in its subtrees, so the very first element is the root. Inorder lists everything in the left subtree, then the root, then everything in the right subtree, so once you know the root you can find it in inorder and split the array cleanly into left and right parts.

That split also tells you sizes. If the root sits at index mid in inorder, the left subtree has exactly mid nodes. In preorder, after the root comes the entire left subtree and then the entire right subtree, so the next mid elements, preorder[1:mid + 1], are the left subtree's preorder and everything after is the right subtree's preorder.

Now you have two smaller instances of the same problem, each with a matching preorder and inorder pair. Recurse on both, attach the results as the root's children, and stop when an array is empty. This is classic divide and conquer, and the reference solution writes it in the most readable way, with list slicing and inorder.index. That costs extra time on lopsided trees, which a hash map of inorder positions and index bounds can remove.

Approach: Recursive divide and conquer with slicing

  1. If either array is empty, return None because there is no subtree to build.
  2. Create the root from preorder[0], since preorder always starts with the root.
  3. Find mid = inorder.index(preorder[0]). Everything left of mid in inorder belongs to the left subtree, and everything right of it belongs to the right subtree.
  4. Build the left child from preorder[1:mid+1] and inorder[:mid], which both contain exactly the mid left-subtree nodes.
  5. Build the right child from preorder[mid+1:] and inorder[mid+1:].
  6. Return the root with both children attached.

Step-by-step example

preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
  1. The root is 3. It sits at index 1 in inorder, so the left subtree has one node.
  2. The left call gets preorder [9] and inorder [9]. It makes node 9, and both of its recursive calls receive empty arrays and return None.
  3. The right call gets preorder [20,15,7] and inorder [15,20,7]. Its root is 20, found at index 1 of that inorder slice.
  4. Inside that call, the left child is built from [15] and [15], and the right child from [7] and [7].
  5. The final tree is 3 with left child 9 and right child 20, and 20 has children 15 and 7, which is [3,9,20,null,null,15,7] in level order.

Code: Python, Java, C++

1class Solution:
2    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
3        if not preorder or not inorder:
4            return None
5            
6        root = TreeNode(preorder[0])
7        mid = inorder.index(preorder[0])
8        
9        root.left = self.buildTree(preorder[1:mid+1], inorder[:mid])
10        root.right = self.buildTree(preorder[mid+1:], inorder[mid+1:])
11        
12        return root

Time and space complexity

Time

O(n²)

Each call does a linear inorder.index search and copies slices proportional to its subtree size. On a skewed tree those costs add up to n + (n - 1) + (n - 2) and so on, which is quadratic. A balanced tree costs O(n log n).

Space

O(n²)

Every active call on the recursion stack holds its own copied slices. On a skewed tree the stack is n deep with slices of shrinking size, so the worst case is quadratic. Balanced trees need O(n log n).

Other approaches

Hash map of inorder indices with bounds (time O(n), space O(n))

Precompute a map from value to inorder index and recurse with left and right inorder bounds plus a shared pointer into preorder that advances each time a node is created. No slicing and no linear search are needed, so the build is linear.

Iterative build with a stack (time O(n), space O(n))

Walk preorder, pushing nodes as left children until the top of the stack matches the next inorder value, then pop while it matches and attach the next preorder value as a right child. It is linear and avoids recursion but is harder to explain.

Common mistakes

  • Slicing preorder as preorder[1:mid] instead of preorder[1:mid+1]. The left subtree has mid nodes starting at index 1, so the end index is mid + 1.
  • Recursing on the right subtree before the left in the pointer-based version. Preorder lists the left subtree first, so the shared index must be consumed left first.
  • Assuming this works with duplicate values. With duplicates, inorder.index can find the wrong occurrence and the tree is no longer uniquely determined.
  • Calling this solution O(n). The slicing and linear search make it O(n²) in the worst case.

Frequently asked questions

Why do you need both preorder and inorder to build the tree?

Preorder tells you which node is the root of each subtree, while inorder tells you which nodes fall on the left and which on the right. Neither alone is enough to pin down a unique shape when values are distinct.

How do you make the construction O(n)?

Store each value's inorder index in a hash map so you can find the root position in constant time, and pass index bounds instead of slicing arrays. Then each node is created once with constant work.

Can you build a tree from preorder and postorder?

Not uniquely in general. Without inorder, a node with a single child is ambiguous because you cannot tell whether the child is on the left or the right. It works only when every node has zero or two children.