← Questions
Construct binary tree from inorder and postorder traversal
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Nvidia's technical phone screen, last asked Aug 2025. It tests binary trees, recursion and hash maps.
Given the inorder and postorder traversals of a binary tree whose values are all distinct, rebuild the tree and return its root.
Interface
Unless you agree on a different interface with the interviewer, assume:
build_tree(inorder: list[int], postorder: list[int]) -> TreeNode | None
For checking, write the result in level order with None for missing children and trailing Nones trimmed.
Example
inorder = [9, 3, 15, 20, 7]
postorder = [9, 15, 7, 20, 3]
# 3
# / \
# 9 20
# / \
# 15 7
build_tree(inorder, postorder) -> [3, 9, 20, None, None, 15, 7]
build_tree([-1], [-1]) -> [-1]
Constraints
-
1 <= n <= 3000; values are distinct, between -3000 and 3000. - The two arrays are guaranteed to be valid traversals of the same tree.
Clarifying questions
- Are values distinct (without that the tree is not unique)?
- Can the input be empty or invalid, and should invalid input be detected?
- How deep can the tree be (recursion limits)?
What a strong answer covers
- The key fact: the last postorder value is the root, and its position in inorder splits the left and right subtrees, whose sizes then split postorder.
- A first version with list slicing, and why it is
O(n^2)in time and memory. - The linear version: a value-to-index map over inorder, index bounds instead of slices, and consuming postorder from the right, building the right subtree before the left.
-
O(n)time and space, and an iterative version or raised recursion limit for skewed trees. - Tests for a single node, a left-skewed and a right-skewed tree.
Follow-ups
- Rebuild from preorder and inorder instead.
- Why can preorder and postorder alone not determine the tree in general?
- Detect inputs that are not consistent traversals of one tree.
Where it's asked
- Nvidia · Technical phone screen · Last asked Aug 2025Live technical interview, 45 to 90 minutes; a project discussion, then a small task
What it tests
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
