Skip to the solution
MediumDSA12 min read

How do you build a binary tree from preorder and inorder traversals?

179 views

The problem

Question presented to candidate: "I give you two arrays: the preorder and the inorder traversal of a binary tree whose values are all distinct. Write a Python function that rebuilds the tree and returns its root."

What a strong answer should cover:

  • Preorder's first value is the root; finding that value in inorder splits the remaining values into the left subtree (before it) and the right subtree (after it).
  • Recurse on the two parts; the left subtree's preorder comes first, so build left before right while consuming preorder with one moving index.
  • A value โ†’ index hash map makes each split O(1), giving O(n) total; a linear search per node is O(nยฒ) on a skewed tree.
  • Pass index ranges instead of copying sub-arrays.
  • Why the values must be distinct (duplicates make the answer ambiguous) and why preorder + postorder alone is not enough in general.
  • Python specifics: a dict comprehension for the index map, nonlocal for the shared preorder index, and why inorder.index(...) plus slicing (preorder[1:mid + 1]) quietly makes it O(nยฒ).

Clarifying questions expected:

  • Are all values distinct, and are the two arrays guaranteed to describe the same tree?
  • How large can n be (is recursion depth a concern)?

Code / implementation expected: Yes โ€” a recursive helper over inorder index ranges with a dict for positions, in Python 3.

  • trees
  • construction

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

12 min read ยท 11 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonRebuild from preorder + inorder with an index map (6 cases)
PythonLinear scan vs hash map, and why duplicates break it

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 118 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you find the top K frequent elements?

Continue