Uber · Question 52 · Trees
Construct Binary Tree from Preorder and Inorder
Problem
Given preorder and inorder traversal of a binary tree, construct the original tree.
Approach
First node in preorder is root. Use hashmap to find root index in inorder. Recursively build left and right subtrees using sliced lists or indices.
Time O(n)Space O(n)
How it works
- 1The preorder head is the subtree root.
- 2Its inorder index splits left/right ranges.
- 3Recurse with index ranges (O(1) lookup via hashmap).
Sample input / output
Input: 5 3 9 20 15 7 5 9 3 15 20 7 Output: [3, 9, 20, None, None, 15, 7]
Constraints
1 <= nodes <= 3000; unique values; valid traversals.
Solution — read it, then walk it
Time O(n)Space O(n)Loops 2Branches 5Returns 5source · Python
Scroll sideways for wide charts — the view follows the active step.
- start / end
- statement
- condition
- loop
- returns
- definition
1/45
StartSTART
Interactive control-flow diagram and step-by-step code walkthrough.
Recommended resourcesAffiliate links · may earn us a commission
Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits