Given two integer arrays preorder and inorder where:
preorder is the preorder traversal of a binary treeinorder is the inorder traversal of the same treeConstruct and return the binary tree.
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
Tree:
3
/ \
9 20
/ \
15 7
Input: preorder = [-1], inorder = [-1]
Output: [-1]
Key Observations:
Algorithm:
Example:
preorder = [3, 9, 20, 15, 7]
inorder = [9, 3, 15, 20, 7]
Step 1: Root = 3 (first in preorder)
Step 2: Find 3 in inorder → splits at index 1
left_inorder = [9]
right_inorder = [15, 20, 7]
Step 3: Split preorder accordingly:
left_preorder = [9] (next 1 element)
right_preorder = [20, 15, 7] (remaining)
Step 4: Recursively build subtrees
This is a Divide and Conquer + Tree Construction problem:
Preprocess: Create hashmap of value → index in inorder (O(1) lookup)
Recursive Function: build(pre_start, pre_end, in_start, in_end)
Initial Call: build(0, n-1, 0, n-1)
Time Optimization: HashMap for O(1) lookup instead of O(n) search.
Time: O(n) where n = number of nodes
Space: O(n)