Reconstruct Binary Tree from Inorder and Postorder Sequences
Trees & GraphsModel answerLast updated
Reconstruct a binary tree given its inorder and postorder traversal arrays, assuming all node values are unique.
Given two integer arrays, inorder and postorder, representing the inorder and postorder traversals of the same binary tree respectively, reconstruct and return the original binary tree.
Assumptions & Constraints
1 <= inorder.length <= 3000postorder.length == inorder.length-3000 <= inorder[i], postorder[i] <= 3000- All values in
inorderandpostorderare unique. - It is guaranteed that
inorderandpostorderform a valid binary tree.
Example 1
Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
Output: [3,9,20,null,null,15,7]
Example 2
Input: inorder = [-1], postorder = [-1]
Output: [-1]
Hints
Hint 1
Recall what the last element of a postorder traversal represents.
Hint 2
How does finding the root value in the inorder sequence divide the tree into left and right subtrees?
Hint 3
If you consume the postorder array backwards, which subtree's root do you encounter first: left or right?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach 1: Recursive Approach with Hash Map Optimization (Optimal)
Explanation
To reconstruct a binary tree uniquely from traversals, we need to leverage the structural properties of each traversal:
- Postorder (
left -> right -> root): The last element of any postorder range is always the root node of that subtree. - Inorder (
left -> root -> right): Locating the root node's value in the inorder traversal cleanly partitions the array into the left subtree items (all elements to the left of the root) and the right subtree items (all elements to the right of the root).
By maintaining a pointer moving backwards from the end of the postorder array, we process roots sequentially. Because postorder in reverse is root -> right -> left, we must construct the right subtree before the left subtree.
To achieve an optimal $O(n)$ time complexity, we preprocess the inorder array into a hash map mapping node value -> inorder index. This allows $O(1)$ lookups instead of scanning the array linearly for each root node.
Algorithm Steps
- Build a hash map
inorder_index_mapmapping each value ininorderto its index. - Initialize a pointer
post_idxtolen(postorder) - 1. - Define a recursive helper function
build(in_left, in_right):- If
in_left > in_right, returnNone(empty subtree). - Read
root_val = postorder[post_idx]and decrementpost_idx. - Create a new
TreeNode(root_val). - Find
index = inorder_index_map[root_val]. - Recursively construct the right child:
node.right = build(index + 1, in_right). - Recursively construct the left child:
node.left = build(in_left, index - 1). - Return the node.
- If
Python 3 Implementation
from typing import List, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
# Pre-hash inorder element positions for O(1) retrieval
inorder_map = {val: idx for idx, val in enumerate(inorder)}
post_idx = len(postorder) - 1
def build(in_left: int, in_right: int) -> Optional[TreeNode]:
nonlocal post_idx
if in_left > in_right:
return None
# Pick the current root value from postorder
root_val = postorder[post_idx]
post_idx -= 1
root = TreeNode(root_val)
pivot = inorder_map[root_val]
# Crucial: Build right subtree before left subtree because
# reverse postorder visits root -> right -> left.
root.right = build(pivot + 1, in_right)
root.left = build(in_left, pivot - 1)
return root
return build(0, len(inorder) - 1)
Complexity Analysis
- Time Complexity: $\mathcal{O}(n)$, where $n$ is the number of nodes in the binary tree. Creating the index lookup map takes $\mathcal{O}(n)$ time, and each node is processed exactly once in constant time.
- Space Complexity: $\mathcal{O}(n)$. The hash map uses $\mathcal{O}(n)$ space. The call stack uses $\mathcal{O}(h)$ space, where $h$ is the tree height ($\mathcal{O}(\log n)$ on average, $\mathcal{O}(n)$ worst-case for degenerate trees).
Approach 2: Iterative Approach Using a Stack
Explanation
An iterative alternative avoids call stack overflow on deeply skewed trees. We iterate through postorder in reverse order while scanning inorder backwards using a stack.
- The last element of
postorderis the root. Push it onto the stack. - Move backwards through
postorder. For each node value:- If the top of the stack does not match the current element in
inorder, the new node is the right child of the stack's top node. - If the top of the stack matches the current element in
inorder, keep popping nodes from the stack while they match. The new node becomes the left child of the last popped node.
- If the top of the stack does not match the current element in
- Push the new node onto the stack.
Python 3 Implementation
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
if not postorder:
return None
root = TreeNode(postorder[-1])
stack = [root]
inorder_ptr = len(inorder) - 1
for post_val in reversed(postorder[:-1]):
node = TreeNode(post_val)
last_popped = None
# Check if we have finished processing the right boundary
while stack and stack[-1].val == inorder[inorder_ptr]:
last_popped = stack.pop()
inorder_ptr -= 1
if last_popped:
last_popped.left = node
else:
stack[-1].right = node
stack.append(node)
return root
Complexity Analysis
- Time Complexity: $\mathcal{O}(n)$, since each node is pushed to and popped from the stack at most once.
- Space Complexity: $\mathcal{O}(n)$ to hold the stack of tree nodes.
Key Takeaways & Edge Cases
- Uniqueness: Unique values are necessary to build a deterministic binary tree. If duplicate values exist, an inorder index lookup is ambiguous.
- Order of Subtree Calls: When traversing
postorderfrom back to front, you encounter right children before left children. Invokingbuildon the left child first would misassign elements. - Common Pitfall: Using
inorder.index(val)inside the recursion or slicing arrays (inorder[:mid]) leads to an $\mathcal{O}(n^2)$ runtime due to repeated linear scans and subarray allocations.