LeetCode #105 Medium

Construct BT from Preorder and Inorder

Construct Binary Tree from Preorder and Inorder Traversal is LeetCode 105 (Medium). You get two arrays that describe the same binary tree:

  • preorder lists each node, then its left subtree, then its right subtree.
  • inorder lists each node's left subtree, then the node, then its right subtree.

Rebuild the tree and return its root. All values are distinct, so each value names exactly one node. There are at most 3,000 nodes, and an O(n) build is the expected answer.

Constraints
  • 1 <= preorder.length <= 3000
  • inorder.length == preorder.length
  • -3000 <= preorder[i], inorder[i] <= 3000
  • preorder and inorder consist of unique values.
  • Each value of inorder also appears in preorder.
  • preorder is guaranteed to be the preorder traversal of the tree.
  • inorder is guaranteed to be the inorder traversal of the tree.
treedivide-and-conquerhash-table
Open on LeetCode ↗
02

Intuition

In preorder, every subtree is written as one unbroken block: its root first, then the block of its left subtree, then the block of its right subtree. What preorder does not say is where the left block ends.

Inorder answers that. It writes the left subtree, then the root, then the right subtree, so the root's position in inorder tells you how many values sit in its left subtree. Both arrays then split into left and right parts of matching sizes, and each part is solved the same way.

One shared index reading preorder from the front hands out roots in the order the recursion needs: a root, its whole left subtree, then its whole right subtree.

How to spot this pattern

Two listings of the same tree, one fixing the order of the roots and the other fixing the size of each side, point to divide and conquer on index ranges. A map from value to position turns each split into a single lookup.

03

Approach

Try it first

Before reading on, take preorder [3, 9, 20, 15, 7] and inorder [9, 3, 15, 20, 7]. Decide which value is the root, how many values belong to its left subtree, and which preorder values those are. Then repeat the same reasoning for the right part.

1

Record where each value sits in inorder

Build a map from each value to its index in inorder, once. Every call needs its root's position, and the map answers that in O(1) instead of a scan.

2

Describe a subtree by its inorder range

build(lo, hi) builds the subtree whose values are inorder[lo..hi]. When lo > hi the range holds no values, so the call returns nothing and leaves the preorder index where it is.

3

Take the next preorder value as the root

Make a node from preorder[i] and move i forward by one. Preorder writes a subtree's root before anything else in it, so the next unread value is always the root of the range this call is building.

4

Build the left side, then the right side

Look up the root's position mid. Build node.left from lo..mid - 1, then node.right from mid + 1..hi. Preorder lists the whole left block before the right block, so the shared index meets the left subtree's values first.

5

Start with the whole array

With i = 0, call build(0, n - 1) and return the node it creates. That node holds preorder[0], the overall root.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
▶3 pos = {v: k for k, v in enumerate(inorder)}
▶4 i = 0
▶5 
▶6 def build(lo, hi):
▶7 nonlocal i
▶8 if lo > hi:
▶9 return None
▶10 node = TreeNode(preorder[i])
▶11 i += 1
▶12 mid = pos[node.val]
▶13 node.left = build(lo, mid - 1)
▶14 node.right = build(mid + 1, hi)
▶15 return node
▶16 
▶17 return build(0, len(inorder) - 1)
preorderinorder39201579315207first preorder value, 3, will be the root
i0
range0..4
Two listings of one tree. Preorder writes every subtree as a block that starts with its root. Inorder will tell us how long each subtree's left block is. A map from value to inorder position is built first, so each root is found in one step.
preorderinorder39201579315207left 1left 1right 3right 333 is next in preorder → 1 left, 3 right
root3
mid1
range0..4
3 is the next unread preorder value, so it is the root of this range. In inorder it sits at position 1: 1 value to its left and 3 to its right. So in preorder, the next 1 value is its left subtree and the 3 after it its right subtree.
preorderinorder39201579315207399 is next in preorder → none left, none right
root9
mid0
range0..0
9 is the next unread preorder value, so it is the root of this range, hung as the left child of 3. In inorder it sits at position 0: nothing to its left and nothing to its right. So in preorder, the next zero values are its left subtree.
preorderinorder3920157931520739no values left of 9 → empty
rangeempty
i2
In inorder, nothing sits on the left of 9 inside its range, so its left subtree has no values. Return nothing, and leave the preorder index where it is: the next value belongs to someone else.
preorderinorder3920157931520739no values right of 9 → empty
rangeempty
i2
In inorder, nothing sits on the right of 9 inside its range, so its right subtree has no values. Return nothing, and leave the preorder index where it is: the next value belongs to someone else.
preorderinorder39201579315207left 1left 1right 1right 1392020 is next in preorder → 1 left, 1 right
root20
mid3
range2..4
20 is the next unread preorder value, so it is the root of this range, hung as the right child of 3. In inorder it sits at position 3: 1 value to its left and 1 to its right. So in preorder, the next 1 value is its left subtree and the 1 after it its right subtree.
preorderinorder3920157931520739201515 is next in preorder → none left, none right
root15
mid2
range2..2
15 is the next unread preorder value, so it is the root of this range, hung as the left child of 20. In inorder it sits at position 2: nothing to its left and nothing to its right. So in preorder, the next zero values are its left subtree.
preorderinorder39201579315207392015no values left of 15 → empty
rangeempty
i4
In inorder, nothing sits on the left of 15 inside its range, so its left subtree has no values. Return nothing, and leave the preorder index where it is: the next value belongs to someone else.
preorderinorder39201579315207392015no values right of 15 → empty
rangeempty
i4
In inorder, nothing sits on the right of 15 inside its range, so its right subtree has no values. Return nothing, and leave the preorder index where it is: the next value belongs to someone else.
preorderinorder3920157931520739201577 is next in preorder → none left, none right
root7
mid4
range4..4
7 is the next unread preorder value, so it is the root of this range, hung as the right child of 20. In inorder it sits at position 4: nothing to its left and nothing to its right. So in preorder, the next zero values are its left subtree.
preorderinorder392015793152073920157no values left of 7 → empty
rangeempty
i5
In inorder, nothing sits on the left of 7 inside its range, so its left subtree has no values. Return nothing, and leave the preorder index where it is: the next value belongs to someone else.
preorderinorder392015793152073920157no values right of 7 → empty
rangeempty
i5
In inorder, nothing sits on the right of 7 inside its range, so its right subtree has no values. Return nothing, and leave the preorder index where it is: the next value belongs to someone else.
preorderinorder392015793152073920157all 5 values placed → return root 3
root3
Every value is placed. Each node took the next preorder value, and its inorder position fixed how many values went to each side, so this is the only tree with both listings. Return the root, 3.
05

Common pitfalls

Building the right side before the left

✗ Wrong
node.right = build(mid + 1, hi)
node.left = build(lo, mid - 1)
✓ Right
node.left = build(lo, mid - 1)
node.right = build(mid + 1, hi)

The shared index then hands the left subtree's values to the right side. On preorder [3, 9, 20, 15, 7], the right side of 3 should be 20, 15 and 7, but the next value read is 9, so 9 becomes the root of a side it does not belong to and the tree comes out wrong.

Giving each call its own copy of the index

✗ Wrong
def build(i, lo, hi):
    ...
    node.left = build(i + 1, lo, mid - 1)
    node.right = build(i + 1, mid + 1, hi)
✓ Right
nonlocal i  # one index that every call moves forward

The right side cannot start at i + 1; it starts after however many values the left side used, and a copied index cannot know that number. On [3, 9, 20, 15, 7] both children of 3 read 9 as their root.

Slicing preorder one value short

✗ Wrong
node.left = self.buildTree(preorder[1:mid], inorder[:mid])
✓ Right
node.left = self.buildTree(preorder[1:mid + 1], inorder[:mid])

The left subtree has mid values, and they sit right after the root, at indexes 1 to mid. Cutting at mid drops one. On [3, 9, 20, 15, 7] and [9, 3, 15, 20, 7], mid is 1, so the left call gets an empty preorder, returns nothing, and 9 never appears in the tree.

06

Edge cases

A chain of 3,000 nodes

When every node has only a left child, each call recurses once more, so the recursion is 3,000 calls deep. That is fine in C++ and Java; plain Python stops at depth 1,000, so raise the limit with sys.setrecursionlimit if your runner keeps the default.

07

Complexity

Time
O(n)
Space
O(n)
Each value becomes a node once, and finding its inorder position is one map lookup. The map holds n entries, and the call stack is as deep as the tree is tall.
08

Construct BT from Preorder and Inorder FAQ

Which pairs of traversals determine a unique binary tree?

A pair that includes inorder: inorder with preorder (this problem), or inorder with postorder. Preorder with postorder is not enough in general: preorder [1, 2] and postorder [2, 1] fit both a tree where 2 is the left child and one where it is the right child.

Can the tree be rebuilt from preorder alone?

Not for a general binary tree, because preorder never says where a left subtree ends. It can for a binary search tree, since the values themselves split the sides: everything smaller than a node goes left.