Construct Binary Tree from Inorder and Postorder Traversal - Problem
Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree.
You may assume that duplicates do not exist in the tree.
A binary tree can be uniquely determined by its inorder and postorder traversals because:
- The last element in postorder 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
Input & Output
Example 1 — Basic Tree
$
Input:
inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
›
Output:
[3,9,20,null,null,15,7]
💡 Note:
The last element 3 in postorder is the root. In inorder, 3 splits the array: [9] (left subtree) and [15,20,7] (right subtree). Recursively apply the same logic.
Example 2 — Single Node
$
Input:
inorder = [-1], postorder = [-1]
›
Output:
[-1]
💡 Note:
Only one node, which is both root and the entire tree.
Example 3 — Linear Tree
$
Input:
inorder = [1,2,3], postorder = [1,3,2]
›
Output:
[2,1,3]
💡 Note:
Root is 2. In inorder: [1] is left subtree, [3] is right subtree. Creates a balanced tree with 2 as root.
Constraints
- 1 ≤ inorder.length ≤ 3000
- postorder.length == inorder.length
- -3000 ≤ inorder[i], postorder[i] ≤ 3000
- inorder and postorder consist of unique values
- Each value of postorder also appears in inorder
- inorder is guaranteed to be the inorder traversal of the tree
- postorder is guaranteed to be the postorder traversal of the same tree
Visualization
Tap to expand
Understanding the Visualization
1
Input
Two arrays: inorder [9,3,15,20,7] and postorder [9,15,7,20,3]
2
Key Insight
Last element of postorder (3) is root; inorder splits into left [9] and right [15,20,7]
3
Output
Reconstructed tree: [3,9,20,null,null,15,7]
Key Takeaway
🎯 Key Insight: Postorder's last element reveals the root, inorder reveals the left/right split boundaries
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code