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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code