Construct Binary Tree from Preorder and Inorder Traversal - Problem

Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

Key insights:

  • The first element in preorder is always the root
  • Elements to the left of root in inorder form the left subtree
  • Elements to the right of root in inorder form the right subtree
  • We can recursively apply this pattern to build the entire tree

Input & Output

Example 1 — Basic Tree
$ Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
💡 Note: Root is 3 (first in preorder). In inorder, 9 is left subtree, [15,20,7] is right subtree. Recursively build: left child 9, right child 20 with children 15,7.
Example 2 — Linear Tree
$ Input: preorder = [1,2,3], inorder = [3,2,1]
Output: [1,2,null,3]
💡 Note: Root 1, left subtree [3,2], no right. Root 2 has left child 3. Forms a left-leaning tree.
Example 3 — Single Node
$ Input: preorder = [1], inorder = [1]
Output: [1]
💡 Note: Single node tree - root is 1 with no children.

Constraints

  • 1 ≤ preorder.length ≤ 3000
  • inorder.length == preorder.length
  • -3000 ≤ preorder[i], inorder[i] ≤ 3000
  • preorder and inorder consist of unique values
  • Each value of inorder also appears in preorder
  • preorder is guaranteed to be the preorder traversal of the tree
  • inorder is guaranteed to be the inorder traversal of the same tree

Visualization

Tap to expand
Binary Tree Reconstruction from Preorder and Inorderpreorder: [3,9,20,15,7]inorder: [9,3,15,20,7]↓ Reconstruction Process ↓3920157Result Tree[3,9,20,null,null,15,7]Tree successfully reconstructed from traversal arrays!
Understanding the Visualization
1
Input Arrays
Preorder [3,9,20,15,7] and Inorder [9,3,15,20,7]
2
Pattern Recognition
First in preorder = root, inorder splits subtrees
3
Tree Output
Reconstructed binary tree [3,9,20,null,null,15,7]
Key Takeaway
🎯 Key Insight: Preorder gives root order, inorder reveals left/right subtree boundaries
Asked in
Facebook 45 Amazon 38 Google 32 Microsoft 28
239.2K Views
High Frequency
~25 min Avg. Time
8.5K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen