Construct Tree From Preorder and Inorder Traversal
Consume preorder roots within exact inorder ranges, build children in the required order, and validate compatibility rather than only matching value sets.
QuestionInterview executionCoding practice
Published ·31 min read·Core·Mixed
ML breadth · active recall
Practice before you read
8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.
The next preorder value becomes a root, and its inorder position partitions the exact ranges passed to its left and right recursive calls.
Problem trace
Consume preorder roots inside their exact inorder ranges, left child before right
Read it this way:With distinct values, preorder picks each next root. Its position in the current inorder range separates child membership. Consume the entire left range before the right, advancing one shared preorder cursor. A root outside its assigned range makes the traversals incompatible, even if their value sets match. The worked range trace constructs all five nodes. Can preorder position alone determine how many of these nodes belong to the left subtree?
Sources and provenance
Full interview answer 31 min read
Reconstruct the unique binary tree described by compatible preorder and inorder traversals with distinct values.
Problem
Input. Two integer lists, preorder and inorder, describing the same finite binary tree with unique values.
Output. Return the root of a newly allocated tree with exactly those traversals.
Rules. Preorder visits root, left subtree, then right subtree.
Inorder visits left subtree, root, then right subtree.
The tree need not be a BST. Assume compatible inputs; leave both lists unchanged.
Two empty lists return None. Every nonempty result node must be newly created.
Example. Preorder [3, 9, 20, 15, 7] and inorder [9, 3, 15, 20, 7] reconstruct root 3.
Its children are 9 and 20; node 20 has children 15 and 7.
Picture
Preorder is [3,9,20,15,7]; inorder is [9,3,15,20,7].
Root three splits inorder at index one. Consume the entire left subtree before reading the right subtree’s root.
Read from preorder
Inclusive inorder range
Split
3
[0,4]
[9], root 3, [15,20,7]
9
[0,0]
Empty, root 9, empty
20
[2,4]
[15], root 20, [7]
15
[2,2]
Two empty child ranges
7
[4,4]
Two empty child ranges
Problem trace
Consume preorder roots inside their exact inorder ranges, left child before right
Input and goalRebuild a binary tree from its preorder and inorder value lists. Values are unique.
Initialize traversal stateBuild the inorder position map, set preorder_index=0, and call build(0,4).
Unique node values are given in preorder and inorder, so root order and left/right membership complement each other to determine one binary tree.
Keep true
build(left,right) consumes exactly the next preorder values belonging to inorder[left:right+1] and returns precisely that subtree. Empty ranges consume nothing and return None.
Reuse it
Combine one traversal that selects the next root with another that partitions membership, and recurse on index ranges; the same decomposition works with inorder plus postorder by choosing roots from the opposite end.
Build the inorder position map, set preorder_index=0, and call build(0,4). Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does preorder choose root 3 while inorder determines which values belong in each subtree?
Reference drawing
Problem trace
Consume preorder roots inside their exact inorder ranges, left child before right
Execution trace
Input and goalRebuild a binary tree from its preorder and inorder value lists. Values are unique.
Initialize traversal stateBuild the inorder position map, set preorder_index=0, and call build(0,4).
Unique node values are given in preorder and inorder, so root order and left/right membership complement each other to determine one binary tree.
Keep true
build(left,right) consumes exactly the next preorder values belonging to inorder[left:right+1] and returns precisely that subtree. Empty ranges consume nothing and return None.
Reuse it
Combine one traversal that selects the next root with another that partitions membership, and recurse on index ranges; the same decomposition works with inorder plus postorder by choosing roots from the opposite end.
Build the inorder position map, set preorder_index=0, and call build(0,4). Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does preorder choose root 3 while inorder determines which values belong in each subtree?
Read it this way:With distinct values, preorder picks each next root. Its position in the current inorder range separates child membership. Consume the entire left range before the right, advancing one shared preorder cursor. A root outside its assigned range makes the traversals incompatible, even if their value sets match. The worked range trace constructs all five nodes. Can preorder position alone determine how many of these nodes belong to the left subtree?
Code
Use this node type for a local run.
from dataclasses import dataclass@dataclassclass TreeNode: val: int left: "TreeNode | None" = None right: "TreeNode | None" = None
def build_tree(preorder: list[int], inorder: list[int]) -> TreeNode | None: positions = {value: index for index, value in enumerate(inorder)} preorder_index = 0 def build(left: int, right: int) -> TreeNode | None: nonlocal preorder_index if left > right: return None value = preorder[preorder_index] preorder_index += 1 node = TreeNode(value) middle = positions[value] node.left = build(left, middle - 1) node.right = build(middle + 1, right) return node return build(0, len(inorder) - 1)
Define What Each Call Consumes
build(left, right) returns exactly the subtree represented by that inclusive inorder range. It consumes the next corresponding preorder segment.
An empty range consumes nothing. A nonempty range consumes one root, then recursively consumes left before right.
Unique values make the position map unambiguous. middle is a traversal boundary, not a numeric comparison with the root.
With expected constant-time dictionary operations, construction takes O(n) time. The map and new output each use O(n) storage.
The call stack adds O(h) space for height h. Deep trees can exceed Python’s recursion limit.
Repeated value scans or slicing would add avoidable work and allocations.
Do Not Validate by Sets Alone
Preorder [1,2,3] and inorder [3,1,2] have equal unique values but incompatible child order.
After choosing root one, its left range contains three. The next preorder root two is outside that range.
The reference trusts compatibility; it is not an input validator.
The platform supplies TreeNode with val, left, and right; this snippet assumes that definition.
Recall: Why must preorder build left first? Its next unread values describe the left subtree before any right-subtree values.
Use Inorder and Postorder
Choose this when: The root-order traversal is postorder instead of preorder. Unique, compatible input is still required.
Read postorder backward. Its reversed order is root, right, left, so change both cursor direction and child construction order.
def build_from_postorder(inorder, postorder): positions = {value: index for index, value in enumerate(inorder)} cursor = len(postorder) - 1 def build(left, right): nonlocal cursor if left > right: return None value = postorder[cursor] cursor -= 1 node = TreeNode(value) middle = positions[value] node.right = build(middle + 1, right) node.left = build(left, middle - 1) return node return build(0, len(inorder) - 1)
Postorder [9,15,7,20,3] reconstructs the same pictured tree. Keeping left-first recursion would consume the wrong subtree.
Expected time remains O(n), with O(n) map/output storage and O(h) recursive stack space.
Check Traversal Compatibility
Choose this when: Malformed traversal pairs must return None instead of being trusted.
def build_tree_checked(preorder, inorder): if ( len(preorder) != len(inorder) or len(set(inorder)) != len(inorder) or set(preorder) != set(inorder) ): return None positions = {value: index for index, value in enumerate(inorder)} cursor = 0 def build(left, right): nonlocal cursor if left > right: return None if cursor == len(preorder): raise ValueError("exhausted preorder") value = preorder[cursor] cursor += 1 middle = positions[value] if not left <= middle <= right: raise ValueError("inconsistent range") node = TreeNode(value) node.left, node.right = build(left, middle - 1), build(middle + 1, right) return node try: result = build(0, len(inorder) - 1) return result if cursor == len(preorder) else None except ValueError: return None
Equal lengths, unique values and equal sets are only the preliminary checks. Every consumed root must also lie inside its active range.
The incompatible example returns None. So does valid empty input; this compact interface deliberately does not distinguish those cases.
Inputs must contain hashable integer values. Expected time and storage remain linear; this validator still has the recursive depth limit.
Transfer
Preorder and postorder alone cannot distinguish a single left child from a single right child. Inorder supplies the missing side-membership boundary.