Construct Binary Tree from Preorder and Postorder Traversal - Problem

Given two integer arrays, preorder and postorder where preorder is the preorder traversal of a binary tree of distinct values and postorder is the postorder traversal of the same tree, reconstruct and return the binary tree.

If there exist multiple answers, you can return any of them.

Preorder traversal: Visit root → left subtree → right subtree

Postorder traversal: Visit left subtree → right subtree → root

Input & Output

Example 1 — Basic Tree
$ Input: preorder = [1,2,4,5,3,6,7], postorder = [4,5,2,6,7,3,1]
Output: [1,2,3,4,5,6,7]
💡 Note: Root is 1, left subtree has root 2 with children 4,5, right subtree has root 3 with children 6,7
Example 2 — Single Node
$ Input: preorder = [1], postorder = [1]
Output: [1]
💡 Note: Only one node, so the tree is just a single node with value 1
Example 3 — Linear Tree
$ Input: preorder = [1,2,3], postorder = [3,2,1]
Output: [1,2,null,3]
💡 Note: Root 1 has left child 2, which has left child 3 (forms a left-skewed tree)

Constraints

  • 1 ≤ preorder.length ≤ 30
  • 1 ≤ preorder[i] ≤ 106
  • postorder.length == preorder.length
  • All values in preorder and postorder are distinct
  • It is guaranteed that preorder and postorder represent the same binary tree

Visualization

Tap to expand
Tree Construction from Preorder and PostorderPreorder:12453Postorder:45231Reconstructed Tree12345Key Insight:• Preorder: Root comes first• Postorder: Root comes last• Find subtree boundaries• Recursively build left & rightOutput (Level Order):[1, 2, 3, 4, 5]
Understanding the Visualization
1
Input Arrays
Preorder and postorder traversals of the same tree
2
Tree Construction
Use preorder for roots and postorder for boundaries
3
Output
Level-order array representation of reconstructed tree
Key Takeaway
🎯 Key Insight: Use preorder for root identification and postorder boundaries to efficiently divide and conquer the tree construction
Asked in
Google 12 Amazon 8 Facebook 6 Microsoft 5
124.0K Views
Medium Frequency
~25 min Avg. Time
2.8K 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