TRT
Sign in
mediumCoreLeetCode#divide and conquer#index map

Construct binary tree from preorder and inorder traversal

Rebuild a binary tree from its preorder and inorder traversals, using the root from preorder to split the inorder list.

The Runtime Theory Team1 min read
Taught inVocabulary and traversalsPro — members onlyA tree is nodes joined by parent-child links with no cycles. Visiting every node is a choice of order: before the children, between them, or after them. Each order fits different jobs.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

inpreorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7]

out[3, 9, 20, null, null, 15, 7]

inpreorder = [-1], inorder = [-1]

out[-1]

inpreorder = [1, 2], inorder = [2, 1]

out[1, 2]

Given the preorder and inorder traversals of a binary tree with distinct values, construct and return the tree.

Before you code

Preorder starts with the root. In inorder, everything left of the root belongs to the left subtree and everything right of it to the right subtree. That splits both lists, and each part is the same problem again.

Hints

  1. Build a map from value to inorder index, so finding the root's position is O(1).
  2. Recurse with index ranges instead of slicing lists, to stay O(n).
  3. Consume preorder from the front with a single moving index: build the left subtree before the right, because preorder lists it first.

Production & complexity notes

When solving Construct binary tree from preorder and inorder traversal on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Vocabulary and traversals to reinforce the underlying pattern.

What it practices

What each traversal order reveals about a tree's shape, from Vocabulary and traversals.

Not started

Sign in to save your learning progress.

Sign in to save