15% off all plans & roadmaps Use code

See plans

Construct Binary Tree from Preorder and Inorder Traversal

Updated

TL;DR: Rebuild a binary tree from its preorder and inorder traversals. Preorder tells you each subtree's root in order, and a hash map of inorder positions tells you where each subtree starts and ends.

Problem

You are given two integer arrays, preorder and inorder. preorder is the preorder traversal of a binary tree, and inorder is the inorder traversal of the same tree. Build the tree and return its root.

Example 1

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

Example 2

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

Constraints

  • 1 <= preorder.length <= 3000
  • inorder.length == preorder.length
  • -3000 <= preorder[i], inorder[i] <= 3000
  • preorder and inorder consist of unique values.
  • Every value in inorder also appears in preorder.
  • preorder is guaranteed to be a valid preorder traversal of the tree.
  • inorder is guaranteed to be a valid inorder traversal of the same tree.

Constraints that matter

  • n up to 3000 means an O(n^2) solution does about 9 million steps, so it passes. The O(n) answer is still the one to present in an interview.
  • All values are unique, so each value maps to exactly one inorder index. This is what makes a hash map lookup valid.
  • Both arrays are guaranteed valid for one tree, so you never need to check for inconsistent input or handle missing values.
  • The tree can be a straight chain 3000 nodes deep. Recursion depth can reach 3000, which exceeds Python's default limit of 1000, so you must raise it there.
  • Values range from -3000 to 3000, so a plain integer index map or a 6001-slot array both work, and there is no overflow risk.

View on LeetCode

Hints

Hint 1

This is a recursive preorder construction.

Hint 2

Take preorder[0] as the root.

Solution

Intuition

This is a recursive preorder construction. Preorder visits root, then the whole left subtree, then the whole right subtree. So the first unused value in preorder is always the root of the subtree you are building right now.

Picture a long row of numbered seats where each guest's name is on a card, and a separate sign-in sheet lists guests in the order they arrived. The hash map is the table of name-to-seat numbers, and the shared preorder pointer is your finger moving down the sign-in sheet, one guest per node, while the seat numbers split the row into left and right groups.

Preorder alone cannot tell you where the left subtree ends. Inorder can. It lists the left subtree, then the root, then the right subtree. Find the root in inorder and everything to its left is the left subtree, everything to its right is the right subtree.

Take preorder = [3,9,20,15,7] and inorder = [9,3,15,20,7]. The root is 3. In inorder, 3 sits at index 1, so [9] is the left subtree and [15,20,7] is the right subtree. The next preorder value is 9, which builds the left child. Then 20 is the root of the right subtree, and the same split repeats.

Why does this work? Because values are unique, the root's position in inorder is unambiguous. The size of the left part tells you how many preorder values belong to the left subtree. If you build left before right, the shared preorder pointer is exactly where the right subtree's root waits. The only real cost is finding the root in inorder, and a hash map makes that lookup O(1).

Watch the pattern animation

Worked example

Input: preorder = [-1], inorder = [-1]
Output: [-1]
Explanation: The first preorder value, -1, is the root. Its position in inorder is index 0, so nothing lies to its left or right. Both subtrees are empty and the tree is the single node -1.

Approach 1: Brute force: scan and slice

Take preorder[0] as the root. Scan inorder from the left until you hit that value, which gives index k. The left subtree has k nodes, so the next k preorder values and the first k inorder values describe it. The rest describe the right subtree.

Copy those four pieces into new arrays and recurse on each pair. This is the version a beginner writes straight from the definition of the traversals.

Steps

  1. If preorder is empty, return null.
  2. Create a node from preorder[0].
  3. Scan inorder linearly to find the index k of that value.
  4. Copy preorder[1..k] and inorder[0..k-1] into new arrays and build the left child from them.
  5. Copy preorder[k+1..] and inorder[k+1..] into new arrays and build the right child from them.
  6. Return the node.

Dry run

On preorder = [-1], inorder = [-1]:

  1. The arrays are not empty, so create node -1.
  2. Scan inorder. Index 0 holds -1, so k = 0.
  3. Left call gets preorder[1..0] and inorder[0..-1], both empty. It returns null.
  4. Right call gets preorder[1..] and inorder[1..], both empty. It returns null.
  5. Return node -1 with no children, which is [-1].

Complexity

TimeO(n^2)
SpaceO(n^2)

Here n is the number of nodes. Each node triggers one call that scans and copies up to n elements. On a chain-shaped tree the subarray sizes are n, n-1, n-2, and so on, which sums to about n^2 / 2 work. Those copies are all alive at once on the recursion stack for a chain, so extra space is also O(n^2) in the worst case.

PythonTested in our runner

from typing import List, Optional
import sys

sys.setrecursionlimit(10000)

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        if not preorder:
            return None
        root = TreeNode(preorder[0])
        # linear scan for the root in inorder
        k = inorder.index(preorder[0])
        # slicing copies the pieces
        root.left = self.buildTree(preorder[1:1 + k], inorder[:k])
        root.right = self.buildTree(preorder[1 + k:], inorder[k + 1:])
        return root

Approach 2: Index ranges with linear scan

What's slow: every call copies four subarrays, which costs time and memory proportional to the subtree size. None of that copying is needed, because each subarray is a contiguous range of the original arrays.

The insight that fixes it: pass indices instead of arrays. A subtree is fully described by the preorder index of its root and an inorder range [lo, hi]. The left subtree has k - lo nodes, so the right subtree's root sits at preorder index preStart + 1 + (k - lo). The scan for the root still costs O(n) per node.

Steps

  1. Define build(preStart, lo, hi). If lo > hi, return null.
  2. Read the root value at preorder[preStart].
  3. Scan inorder from lo upward until you find the value. Call that index k.
  4. Compute leftSize = k - lo.
  5. Build the left child with build(preStart + 1, lo, k - 1).
  6. Build the right child with build(preStart + 1 + leftSize, k + 1, hi).
  7. Call build(0, 0, n - 1) to start.

Dry run

On preorder = [-1], inorder = [-1], n = 1:

  1. Call build(0, 0, 0). The range is valid, so the root value is preorder[0] = -1.
  2. Scan from lo = 0. inorder[0] matches, so k = 0 and leftSize = 0.
  3. Left call is build(1, 0, -1). lo > hi, so it returns null.
  4. Right call is build(1, 1, 0). lo > hi, so it returns null.
  5. Return node -1, which is [-1].

Complexity

TimeO(n^2)
SpaceO(n)

Here n is the number of nodes. Each call creates one node and scans at most its own inorder range, so a chain-shaped tree costs about n + (n-1) + ... + 1 comparisons, which is O(n^2). No arrays are copied. The only extra memory is the recursion stack, which is as deep as the tree is tall, so O(n) in the worst case.

PythonTested in our runner

from typing import List, Optional
import sys

sys.setrecursionlimit(10000)

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        def build(pre_start: int, lo: int, hi: int) -> Optional[TreeNode]:
            if lo > hi:
                return None
            val = preorder[pre_start]
            k = lo
            while inorder[k] != val:  # linear scan inside the range
                k += 1
            root = TreeNode(val)
            root.left = build(pre_start + 1, lo, k - 1)
            root.right = build(pre_start + 1 + (k - lo), k + 1, hi)
            return root

        return build(0, 0, len(inorder) - 1)
Recursive Preorder Traversal pattern infographic for Construct Binary Tree from Preorder and Inorder Traversal

Solution pattern

Recursive Preorder Traversal

Part of Tree Traversal Patterns (DFS & BFS)

Approach 3: Hash map plus a preorder pointerOptimalRecursive Preorder Traversal

What's slow: the scan that finds the root's inorder index. It repeats for every node and makes a chain-shaped tree cost O(n^2). The values are unique, so that answer never changes and can be computed once.

The insight that fixes it: build a map from value to inorder index before recursing. Then keep one shared pointer into preorder. Each call reads the pointer's value as the root and advances it. Because you build the left subtree before the right one, the pointer always lands on the correct next root, so you never compute preorder offsets.

Steps

  1. Build a map indexOf from each inorder value to its index.
  2. Set a shared preorder pointer preIdx to 0.
  3. Define build(lo, hi). If lo > hi, return null.
  4. Read preorder[preIdx], advance preIdx, and create the node.
  5. Look up the node's inorder index k in the map.
  6. Set left = build(lo, k - 1) first, then right = build(k + 1, hi). The order matters.
  7. Return the node. Start with build(0, n - 1).

Dry run

State on preorder = [-1], inorder = [-1]. The map is {-1: 0} and preIdx starts at 0.

StepCallpreIdx beforeActionResult
1build(0, 0)0Range valid. Read preorder[0] = -1, set preIdx = 1. Lookup gives k = 0.Create node -1
2build(0, -1)1lo > hireturn null, becomes left
3build(1, 0)1lo > hireturn null, becomes right
4return1Attach both nullsReturn node -1

The tree is a single node, which prints as [-1]. Every preorder value was consumed exactly once, since preIdx ended at 1 = n.

Complexity

TimeO(n)
SpaceO(n)

Here n is the number of nodes. Building the map takes n insertions. Each node is created by exactly one non-null call, and each of those does one O(1) map lookup, so there are n real calls and n + 1 calls that return null, which is O(n) in total. The map holds n entries, and the recursion stack is as deep as the tree is tall, which is at most n, so extra space is O(n).

PythonTested in our runner

from typing import List, Optional
import sys

sys.setrecursionlimit(10000)

class Solution:
    def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
        index_of = {val: i for i, val in enumerate(inorder)}
        pre_idx = 0

        def build(lo: int, hi: int) -> Optional[TreeNode]:
            nonlocal pre_idx
            if lo > hi:
                return None
            val = preorder[pre_idx]
            pre_idx += 1
            root = TreeNode(val)
            k = index_of[val]
            # left must be built first: preorder is root, left, right
            root.left = build(lo, k - 1)
            root.right = build(k + 1, hi)
            return root

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

Common mistakes

  • Building the right subtree before the left: root.right = build(k + 1, hi) placed above root.left = build(lo, k - 1). Preorder consumes the left subtree first, so the shared pointer then lands on the wrong values. Always assign left first.
  • Slicing arrays in every call, such as preorder[1:1+k] or Arrays.copyOfRange. Each copy costs O(n), so the whole build becomes O(n^2) time and memory. Pass lo and hi indices instead.
  • Using the inorder index to read preorder, as in preorder[k] for the root. The two arrays are aligned only through subtree sizes. Read the root from a pointer that advances once per created node.
  • Checking the base case after reading preorder[preIdx]. When the range is empty, the pointer may already be past the end, so you get an out-of-range error. Test lo > hi first and return before touching preorder.
  • Forgetting to raise Python's recursion limit. A chain-shaped tree with 3000 nodes recurses 3000 deep and the default limit of 1000 raises RecursionError. Call sys.setrecursionlimit(10000) before recursing.
  • Resetting state incorrectly in C++ or Java fields. If preIdx or the map is not reset at the start of buildTree, a second call on the same Solution object reuses stale values. Reinitialize both at the top of the method.

Edge cases

  • A single node, preorder = [-1], inorder = [-1]: return a node with value -1 and both children null.
  • Left-skewed chain, preorder = [3,2,1], inorder = [1,2,3]: every right range is empty, and the recursion goes 3 deep.
  • Right-skewed chain, preorder = [1,2,3], inorder = [1,2,3]: every left range is empty, and each node has only a right child.
  • Maximum size of 3000 nodes in a chain: recursion depth reaches 3000, so Python needs a higher recursion limit.
  • Negative values and zero, such as preorder = [0,-3,3], inorder = [-3,0,3]: the map keys are plain integers, so negatives need no special handling and the root 0 gets a left child -3 and a right child 3.
  • A perfectly balanced tree such as preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]: the root 3 has left child 9 and right child 20, and 20 has children 15 and 7.

Follow-ups interviewers ask

Can you do it without recursion?
Yes. Keep a stack of nodes and two pointers, one into preorder and one into inorder. Push each new preorder value as the left child of the stack top until the top equals the current inorder value. Then pop while the top still matches inorder, advancing the inorder pointer, and attach the next preorder value as the right child of the last popped node. This is O(n) time and O(h) stack space with no hash map, and it avoids deep recursion.
Can you build the tree from inorder and postorder instead?
Yes. Postorder ends with the root, so you read the postorder array from the right. Each root is followed by the right subtree and then the left one when read backward. So you build the right child before the left child, and the rest of the algorithm is identical.
Can preorder and inorder have repeated values?
Not without extra information. With duplicates, the root's inorder position is ambiguous, so several different trees can produce the same pair of traversals. The unique-values constraint is what makes the map lookup and the answer well defined. With duplicates you would need extra rules or you could only count the possible trees.

Construct Binary Tree from Preorder and Inorder Traversal FAQ

What is the time complexity of Construct Binary Tree from Preorder and Inorder Traversal?

The hash map version runs in O(n) time, where n is the number of nodes. Building the map costs n insertions, and each node is created once with one O(1) lookup. The scan-based versions take O(n^2) in the worst case, which happens on a chain-shaped tree.

Why use a hash map for Construct Binary Tree from Preorder and Inorder Traversal?

Every node needs the inorder index of its value to split the left and right subtrees. Values are unique, so that index never changes, and you can store it once. The map turns a repeated O(n) scan into an O(1) lookup, which drops the total from O(n^2) to O(n).

Can Construct Binary Tree from Preorder and Inorder Traversal be solved in O(1) extra space?

No, not counting the output tree. The recursive solution needs a stack as deep as the tree and a map of n entries. You can drop the map by scanning, but that costs O(n^2) time. Even an iterative version needs an explicit stack of up to O(h) nodes, so true O(1) is not achievable in a simple way.

Why does the order of the two recursive calls matter?

The shared preorder pointer moves forward one value per node created. Preorder lists the whole left subtree before the right subtree. So the left call must run first and consume exactly the left subtree's values. If you swap the calls, the right subtree reads values that belong to the left.

Why does a Python solution to LeetCode 105 need a higher recursion limit?

The input can describe a chain of 3000 nodes, so recursion goes 3000 calls deep. Python's default limit is 1000, which raises a RecursionError on such inputs. Setting sys.setrecursionlimit(10000) fixes it. Java, C++, Go and C# handle this depth with their default stacks.

Do I need both traversals to rebuild the tree?

Yes. Preorder alone cannot tell you where the left subtree ends, so many trees share one preorder. Inorder alone cannot tell you which value is the root. Together they fix the root and the split, so the tree is unique when values are distinct.

Asked at

See which companies ask this — Pro

Practise it