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
Binary Tree from Preorder & Postorder INPUT Preorder Traversal 1 2 4 5 3 6 7 Postorder Traversal 4 5 2 6 7 3 1 Key Properties: - Pre: Root first, then subtrees - Post: Subtrees first, root last Postorder Index Map val: 4 5 2 6 7 3 1 idx: 0 1 2 3 4 5 6 map[4]=0, map[5]=1 map[2]=2, map[6]=3 map[7]=4, map[3]=5 map[1]=6 ALGORITHM STEPS 1 Build Hash Map Map postorder values to indices for O(1) lookup 2 Identify Root preorder[preStart] is root First call: root = 1 3 Find Left Subtree Left child = preorder[preStart+1] Use map to find boundary 4 Recursive Build Build left and right subtrees with computed boundaries Recursive Call Example 1 2 3 left right FINAL RESULT Reconstructed Binary Tree 1 2 3 4 5 6 7 Level Order Output [1, 2, 3, 4, 5, 6, 7] OK - Tree Built! Key Insight: In preorder, after root comes left child. In postorder, left subtree ends where left child appears. Using a hash map for postorder indices reduces lookup from O(n) to O(1), making overall complexity O(n). The boundary calculation: leftSize = postIndex[preorder[preStart+1]] - postStart + 1 TutorialsPoint - Construct Binary Tree from Preorder and Postorder Traversal | Hash Map Optimization Time: O(n) Space: O(n)
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