Construct Binary Tree from Inorder and Postorder Traversal (LeetCode 106): Solution and Explanation
You get the inorder and postorder traversals of a binary tree whose values are all distinct, and you must rebuild the tree. The tree can have up to 3000 nodes, so the rebuild should be linear.
Intuition
Postorder writes a node only after both of its subtrees. So the very last value in postorder is the root of the whole tree, and the same holds for every subtree: the last value of a subtree's postorder block is that subtree's root.
Inorder writes the left subtree, then the node, then the right subtree. Once you know the root, its position in inorder tells you exactly which values belong to the left subtree (everything before it) and which belong to the right subtree (everything after it).
Now read postorder backwards. Reversed, it is root, right subtree, left subtree. If you keep one pointer that walks from the end, the next value it meets is always the root of the subtree you are about to build, as long as you build the right subtree before the left one.
That removes all slicing. Each recursive call only needs a window [lo, hi] of inorder, plus the shared pointer into postorder. A hash map from value to inorder index finds each split in constant time.
Approach: Backward postorder pointer with inorder windows
- Build a map
idxfrom each inorder value to its index. - Set
post = len(postorder) - 1, the root of the whole tree. - Define
build(lo, hi). Iflo > hi, the window is empty, so return null. - Create a node from
postorder[post]and movepostone step left. - Look up
mid = idx[node.val]. The window splits into[lo, mid - 1](left subtree) and[mid + 1, hi](right subtree). - Build the right child from
[mid + 1, hi]first, then the left child from[lo, mid - 1], and return the node. - Return
build(0, n - 1).
Step-by-step example
inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
post= 4, so 3 is the root. In inorder, 3 is at index 1: [9] is its left window and [15,20,7] is its right window.- Build the right side first.
post= 3 gives 20, found at inorder index 3, splitting [2,4] into [15] on the left and [7] on the right. - Still on the right:
post= 2 gives 7, the only value in window [4,4]. Both of its windows are empty, so it is a leaf and becomes 20's right child. post= 1 gives 15 for window [2,2]. It is a leaf and becomes 20's left child. 20's subtree is complete and attaches as 3's right child.- Finally the left window [0,0]:
post= 0 gives 9, a leaf attached as 3's left child. The tree serializes to [3,9,20,null,null,15,7].
Code: Python, Java, C++
1class Solution:
2 def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
3 idx = {v: i for i, v in enumerate(inorder)}
4 self.post = len(postorder) - 1
5
6 def build(lo: int, hi: int) -> Optional[TreeNode]:
7 if lo > hi:
8 return None
9 root = TreeNode(postorder[self.post])
10 self.post -= 1
11 mid = idx[root.val]
12 root.right = build(mid + 1, hi)
13 root.left = build(lo, mid - 1)
14 return root
15
16 return build(0, len(inorder) - 1)1class Solution {
2 private Map<Integer, Integer> idx;
3 private int[] postorder;
4 private int post;
5
6 public TreeNode buildTree(int[] inorder, int[] postorder) {
7 idx = new HashMap<>();
8 for (int i = 0; i < inorder.length; i++) idx.put(inorder[i], i);
9 this.postorder = postorder;
10 post = postorder.length - 1;
11 return build(0, inorder.length - 1);
12 }
13
14 private TreeNode build(int lo, int hi) {
15 if (lo > hi) return null;
16 TreeNode root = new TreeNode(postorder[post--]);
17 int mid = idx.get(root.val);
18 root.right = build(mid + 1, hi);
19 root.left = build(lo, mid - 1);
20 return root;
21 }
22}1class Solution {
2public:
3 TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
4 idx.clear();
5 for (int i = 0; i < (int)inorder.size(); i++) idx[inorder[i]] = i;
6 post = (int)postorder.size() - 1;
7 return build(postorder, 0, (int)inorder.size() - 1);
8 }
9
10private:
11 unordered_map<int, int> idx;
12 int post = 0;
13
14 TreeNode* build(vector<int>& postorder, int lo, int hi) {
15 if (lo > hi) return nullptr;
16 TreeNode* root = new TreeNode(postorder[post--]);
17 int mid = idx[root->val];
18 root->right = build(postorder, mid + 1, hi);
19 root->left = build(postorder, lo, mid - 1);
20 return root;
21 }
22};Time and space complexity
O(n)
Every value becomes exactly one node, and each split is a constant-time map lookup. Empty windows add at most n + 1 extra calls.
O(n)
The value-to-index map holds n entries, and the recursion goes as deep as the tree height, which is n for a skewed tree.
Other approaches
Slice and search (time O(n²), space O(n²))
Take the last postorder value as the root, find it in inorder with a linear scan, and recurse on sliced copies of both arrays. It is the most direct translation of the definition but copies arrays at every level and scans linearly for each root.
Iterative with a stack (time O(n), space O(n))
Walk postorder backwards while pushing nodes on a stack and use a pointer that walks inorder backwards to decide when to switch from right children to left children. It avoids recursion depth issues but is harder to get right in an interview.
Common mistakes
- Building the left subtree before the right one. With a single backward pointer into postorder, the next values belong to the right subtree, so the left-first order assigns the wrong roots.
- Using
inorder.index(value)inside the recursion. It is a linear scan per node and turns the solution quadratic on large inputs. - Slicing arrays at every call. It is correct but costs O(n) per level in time and memory.
- Forgetting that the pointer must be shared across calls. In Python, a plain local integer inside the nested function needs
nonlocalor an attribute such asself.post.
Frequently asked questions
Why must the right subtree be built first?
Postorder is left, right, root. Reading it from the end gives root, right, left. The pointer only moves one way, so after taking the root it is sitting on the right subtree's values, which have to be consumed before the left subtree's.
Why does the problem require distinct values?
The split relies on finding the root's unique position in inorder. With duplicates, a value could appear in several places and the tree would not be uniquely determined.
Could I rebuild the tree from preorder and postorder instead?
Not uniquely in general. Without inorder you cannot tell whether a lone child is a left or a right child. That variant exists on LeetCode only for full binary trees or when any valid tree is accepted.
How does this differ from the preorder and inorder version?
Preorder puts the root first, so you read it forwards and build the left subtree first. Postorder puts the root last, so you read it backwards and build the right subtree first. The inorder split is identical.