Coding: Build a Binary Tree from Two Traversals
You are given two integer arrays representing traversals of the same binary tree:
-
preorder
: node order is
root → left → right
-
inorder
: node order is
left → root → right
All values are unique.
Task
Reconstruct the binary tree and return its root node.
Input
-
preorder
: length
n
(1 ≤ n ≤ 10^5)
-
inorder
: length
n
-
Values are unique integers.
Output
-
Return the root of the reconstructed binary tree (using a standard
TreeNode { val, left, right }
structure).
Example
-
preorder = [3, 9, 20, 15, 7]
-
inorder = [9, 3, 15, 20, 7]
The reconstructed tree is:
-
root = 3
-
left child = 9
-
right subtree rooted at 20 with children 15 and 7
Notes
-
Assume the input is valid (both traversals come from one binary tree).
-
Your solution should be efficient for large
n
.