Construct Binary Tree from Inorder and Postorder Traversal
Pattern: Construction from traversals
Postorder ends with the root, so read it from the end: root, then the right subtree, then the left. Split by the root's inorder position as before, but build the right subtree first.
The problem
Rebuild the binary tree from its inorder and postorder traversals (values are distinct) and return its root.
inorder = [9, 3, 15, 20, 7], postorder = [9, 15, 7, 20, 3] gives [3, 9, 20, null, null, 15, 7]. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.
Think first
- Where is the root in postorder?
- Read backwards, in what order does postorder list the subtrees?
- So which subtree must be built first?
Hints
Brute force, and why it fails
Search and slice as in the brute force for preorder: O(n²).
The key insight
Reading postorder backwards is preorder of the mirrored tree, so the same method works with the subtrees swapped.
Dry run
| root | 3 |
|---|
inorder [9, 3, 15, 20, 7], postorder [9, 15, 7, 20, 3]. The last value, 3, is the root.
The plan
where = value -> inorder index; next = last postorder index
build(lo, hi): if lo > hi: null
root = postorder[next--]; m = where[root]
root.right = build(m + 1, hi); root.left = build(lo, m - 1)
Complexity
- Time
O(n)- Space
O(n)
Each value once, plus the map.
Edge cases
- One value.
- A chain.
- Empty arrays.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
private int next; // the next postorder value to place, from the end
private Map<Integer, Integer> where; // value -> its index in inorder
public TreeNode buildTree(int[] inorder, int[] postorder) {
next = postorder.length - 1;
where = new HashMap<>();
for (int i = 0; i < inorder.length; i++) where.put(inorder[i], i);
return build(postorder, 0, inorder.length - 1);
}
private TreeNode build(int[] postorder, int lo, int hi) {
if (lo > hi) return null;
TreeNode root = new TreeNode(postorder[next--]); // postorder read backwards: root, right, left
int mid = where.get(root.val);
root.right = build(postorder, mid + 1, hi); // so build the right subtree first
root.left = build(postorder, lo, mid - 1);
return root;
}
}C++
class Solution {
public:
int next; // the next postorder value to place, from the end
unordered_map<int, int> where; // value -> its index in inorder
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
next = static_cast<int>(postorder.size()) - 1;
where.clear();
for (int i = 0; i < static_cast<int>(inorder.size()); i++) where[inorder[i]] = i;
return build(postorder, 0, static_cast<int>(inorder.size()) - 1);
}
TreeNode* build(vector<int>& postorder, int lo, int hi) {
if (lo > hi) return NULL;
TreeNode* root = new TreeNode(postorder[next--]); // postorder read backwards: root, right, left
int mid = where[root->val];
root->right = build(postorder, mid + 1, hi); // so build the right subtree first
root->left = build(postorder, lo, mid - 1);
return root;
}
};Python
from lib import TreeNode
class Solution:
def buildTree(self, inorder: list[int], postorder: list[int]):
where = {v: i for i, v in enumerate(inorder)} # value -> its index in inorder
it = iter(reversed(postorder)) # postorder read backwards: root, right, left
def build(lo, hi):
if lo > hi:
return None
root = TreeNode(next(it))
mid = where[root.val]
root.right = build(mid + 1, hi) # so build the right subtree first
root.left = build(lo, mid - 1)
return root
return build(0, len(inorder) - 1)Common mistakes
- Building the left subtree first.
- Reading postorder from the front.