Construct Binary Tree from Preorder and Inorder Traversal
Construct Binary Tree from Preorder and Inorder 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 preorder and inorder traversals of a binary tree with unique values, rebuild the tree and return its root.
Examples
Example 1
- Input
preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7]- Output
[3, 9, 20, null, null, 15, 7]
Example 2
- Input
preorder = [-1], inorder = [-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²)Each root lookup scans up to n elements.O(h)Take the next preorder value as the root, find it in inorder by scanning, and build the left and right parts recursively.
- root = preorder[pre++]; idx = linear search in inorder[lo..hi].
- left = build(lo, idx - 1); right = build(idx + 1, hi).
class Solution {
private int pre;
public TreeNode buildTree(int[] preorder, int[] inorder) {
pre = 0;
return build(preorder, inorder, 0, inorder.length - 1);
}
private TreeNode build(int[] p, int[] in, int lo, int hi) {
if (lo > hi) return null;
TreeNode root = new TreeNode(p[pre++]);
int idx = lo;
while (in[idx] != root.val) idx++;
root.left = build(p, in, lo, idx - 1);
root.right = build(p, in, idx + 1, hi);
return root;
}
}class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
self.pre = 0
return self.build(preorder, inorder, 0, len(inorder) - 1)
def build(self, p: List[int], ino: List[int], lo: int, hi: int) -> Optional[TreeNode]:
if lo > hi:
return None
root = TreeNode(p[self.pre])
self.pre += 1
idx = lo
while ino[idx] != root.val:
idx += 1
root.left = self.build(p, ino, lo, idx - 1)
root.right = self.build(p, ino, idx + 1, hi)
return rootclass Solution {
private:
int pre;
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
pre = 0;
return build(preorder, inorder, 0, (int)inorder.size() - 1);
}
private:
TreeNode* build(vector<int>& p, vector<int>& in, int lo, int hi) {
if (lo > hi) return nullptr;
TreeNode* root = new TreeNode(p[pre++]);
int idx = lo;
while (in[idx] != root->val) idx++;
root->left = build(p, in, lo, idx - 1);
root->right = build(p, in, idx + 1, hi);
return root;
}
};function buildTree(preorder, inorder) {
let pre = 0;
function build(p, inn, lo, hi) {
if (lo > hi) return null;
const root = new TreeNode(p[pre++]);
let idx = lo;
while (inn[idx] !== root.val) idx++;
root.left = build(p, inn, lo, idx - 1);
root.right = build(p, inn, idx + 1, hi);
return root;
}
return build(preorder, inorder, 0, inorder.length - 1);
}2Optimal (hash map of inorder positions)
O(n)O(n)Same recursion, but look up each root's inorder index in O(1) with a precomputed map. Build the left subtree first, because preorder lists the whole left subtree before the right.
- pos[value] = index in inorder.
- build(lo, hi): root = preorder[pre++]; mid = pos[root]; left = build(lo, mid - 1); right = build(mid + 1, hi).
class Solution {
private int pre;
private final Map<Integer, Integer> pos = new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder) {
for (int i = 0; i < inorder.length; i++) pos.put(inorder[i], i);
pre = 0;
return build(preorder, 0, inorder.length - 1);
}
private TreeNode build(int[] p, int lo, int hi) {
if (lo > hi) return null;
TreeNode root = new TreeNode(p[pre++]);
int mid = pos.get(root.val);
root.left = build(p, lo, mid - 1);
root.right = build(p, mid + 1, hi);
return root;
}
}class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
self.pos = {v: i for i, v in enumerate(inorder)}
self.pre = 0
return self.build(preorder, 0, len(inorder) - 1)
def build(self, p: List[int], lo: int, hi: int) -> Optional[TreeNode]:
if lo > hi:
return None
root = TreeNode(p[self.pre])
self.pre += 1
mid = self.pos[root.val]
root.left = self.build(p, lo, mid - 1)
root.right = self.build(p, mid + 1, hi)
return rootclass Solution {
private:
int pre;
unordered_map<int, int> pos;
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
for (int i = 0; i < (int)inorder.size(); i++) pos[inorder[i]] = i;
pre = 0;
return build(preorder, 0, (int)inorder.size() - 1);
}
private:
TreeNode* build(vector<int>& p, int lo, int hi) {
if (lo > hi) return nullptr;
TreeNode* root = new TreeNode(p[pre++]);
int mid = pos[root->val];
root->left = build(p, lo, mid - 1);
root->right = build(p, mid + 1, hi);
return root;
}
};function buildTree(preorder, inorder) {
let pre = 0;
const pos = new Map();
for (let i = 0; i < inorder.length; i++) pos.set(inorder[i], i);
function build(p, lo, hi) {
if (lo > hi) return null;
const root = new TreeNode(p[pre++]);
const mid = pos.get(root.val);
root.left = build(p, lo, mid - 1);
root.right = build(p, mid + 1, hi);
return root;
}
return build(preorder, 0, inorder.length - 1);
}Edge cases to test
- Skewed trees
- Single node
Hints
Hint 1
preorder[0] is the root. Its position in inorder splits the left subtree from the right one.
FAQ
What is the best time complexity for Construct Binary Tree from Preorder and Inorder Traversal?
Optimal (hash map of inorder positions) runs in O(n) time and O(n) extra space.
Which pattern does Construct Binary Tree from Preorder and Inorder 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 Inorder and Postorder Traversal, Construct Binary Search Tree from Preorder Traversal, Serialize and Deserialize Binary Tree.
Is there a brute force solution for Construct Binary Tree from Preorder and Inorder Traversal?
Yes. Recursive with linear search takes O(n²) time and O(h) space. Take the next preorder value as the root, find it in inorder by scanning, and build the left and right parts recursively.
Which edge cases should I test for Construct Binary Tree from Preorder and Inorder Traversal?
Skewed trees; Single node.