Construct Binary Tree from Inorder and Postorder Traversal
Construct Binary Tree from Inorder and Postorder Traversal is a medium trees & bst problem solved with the tree serialization / deserialization pattern.
The best approach, optimal (hash map of inorder positions), runs in O(n) time and O(n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from recursive with linear search up.
Problem
Given the inorder and postorder traversals of a binary tree with unique values, rebuild the tree and return its root.
Examples
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]
Constraints
1 <= n <= 3000; values are unique.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 10 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Recursive with linear search | O(n²) | O(h) |
| Optimal (hash map of inorder positions) | O(n) | O(n) |
1Recursive with linear search
O(n²)O(h)Take roots from the end of postorder, find each in inorder by scanning, and build the right subtree before the left.
- root = post[p--]; idx = scan inorder.
- right = build(idx + 1, hi); left = build(lo, idx - 1).
class Solution {
private int p;
public TreeNode buildTree(int[] inorder, int[] postorder) {
p = postorder.length - 1;
return build(inorder, postorder, 0, inorder.length - 1);
}
private TreeNode build(int[] in, int[] post, int lo, int hi) {
if (lo > hi) return null;
TreeNode root = new TreeNode(post[p--]);
int idx = lo;
while (in[idx] != root.val) idx++;
root.right = build(in, post, idx + 1, hi);
root.left = build(in, post, lo, idx - 1);
return root;
}
}class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
self.p = len(postorder) - 1
return self.build(inorder, postorder, 0, len(inorder) - 1)
def build(self, ino: List[int], post: List[int], lo: int, hi: int) -> Optional[TreeNode]:
if lo > hi:
return None
root = TreeNode(post[self.p])
self.p -= 1
idx = lo
while ino[idx] != root.val:
idx += 1
root.right = self.build(ino, post, idx + 1, hi)
root.left = self.build(ino, post, lo, idx - 1)
return rootclass Solution {
private:
int p;
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
p = (int)postorder.size() - 1;
return build(inorder, postorder, 0, (int)inorder.size() - 1);
}
private:
TreeNode* build(vector<int>& in, vector<int>& post, int lo, int hi) {
if (lo > hi) return nullptr;
TreeNode* root = new TreeNode(post[p--]);
int idx = lo;
while (in[idx] != root->val) idx++;
root->right = build(in, post, idx + 1, hi);
root->left = build(in, post, lo, idx - 1);
return root;
}
};function buildTree(inorder, postorder) {
let p = postorder.length - 1;
function build(inn, post, lo, hi) {
if (lo > hi) return null;
const root = new TreeNode(post[p--]);
let idx = lo;
while (inn[idx] !== root.val) idx++;
root.right = build(inn, post, idx + 1, hi);
root.left = build(inn, post, lo, idx - 1);
return root;
}
return build(inorder, postorder, 0, inorder.length - 1);
}2Optimal (hash map of inorder positions)
O(n)O(n)Precompute value → inorder index. Walk postorder backwards, building right before left.
- pos map from inorder.
- build(lo, hi): root = post[p--]; mid = pos[root]; right = build(mid + 1, hi); left = build(lo, mid - 1).
class Solution {
private int p;
private final Map<Integer, Integer> pos = new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
for (int i = 0; i < inorder.length; i++) pos.put(inorder[i], i);
p = postorder.length - 1;
return build(postorder, 0, inorder.length - 1);
}
private TreeNode build(int[] post, int lo, int hi) {
if (lo > hi) return null;
TreeNode root = new TreeNode(post[p--]);
int mid = pos.get(root.val);
root.right = build(post, mid + 1, hi);
root.left = build(post, lo, mid - 1);
return root;
}
}class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
self.pos = {v: i for i, v in enumerate(inorder)}
self.p = len(postorder) - 1
return self.build(postorder, 0, len(inorder) - 1)
def build(self, post: List[int], lo: int, hi: int) -> Optional[TreeNode]:
if lo > hi:
return None
root = TreeNode(post[self.p])
self.p -= 1
mid = self.pos[root.val]
root.right = self.build(post, mid + 1, hi)
root.left = self.build(post, lo, mid - 1)
return rootclass Solution {
private:
int p;
unordered_map<int, int> pos;
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
for (int i = 0; i < (int)inorder.size(); i++) pos[inorder[i]] = i;
p = (int)postorder.size() - 1;
return build(postorder, 0, (int)inorder.size() - 1);
}
private:
TreeNode* build(vector<int>& post, int lo, int hi) {
if (lo > hi) return nullptr;
TreeNode* root = new TreeNode(post[p--]);
int mid = pos[root->val];
root->right = build(post, mid + 1, hi);
root->left = build(post, lo, mid - 1);
return root;
}
};function buildTree(inorder, postorder) {
let p = postorder.length - 1;
const pos = new Map();
for (let i = 0; i < inorder.length; i++) pos.set(inorder[i], i);
function build(post, lo, hi) {
if (lo > hi) return null;
const root = new TreeNode(post[p--]);
const mid = pos.get(root.val);
root.right = build(post, mid + 1, hi);
root.left = build(post, lo, mid - 1);
return root;
}
return build(postorder, 0, inorder.length - 1);
}Edge cases to test
- Skewed trees
Hints
Hint 1
The root is the last postorder value. Reading postorder from the end gives root, right subtree, left subtree, so build the right side first.
FAQ
What is the best time complexity for Construct Binary Tree from Inorder and Postorder Traversal?
Optimal (hash map of inorder positions) runs in O(n) time and O(n) extra space.
Which pattern does Construct Binary Tree from Inorder and Postorder Traversal use?
It is a trees & bst problem that uses the tree serialization / deserialization pattern. Other problems with the same pattern: Construct Binary Tree from Preorder and Inorder Traversal, Construct Binary Search Tree from Preorder Traversal, Serialize and Deserialize Binary Tree.
Is there a brute force solution for Construct Binary Tree from Inorder and Postorder Traversal?
Yes. Recursive with linear search takes O(n²) time and O(h) space. Take roots from the end of postorder, find each in inorder by scanning, and build the right subtree before the left.
Which edge cases should I test for Construct Binary Tree from Inorder and Postorder Traversal?
Skewed trees.