105. Construct Binary Tree from Preorder and Inorder Traversal
Medium NeetCode 150 ↗ Open on LeetCode Source: NeetCode 150
Quick review
- Pattern
- Trees
- Time
- O(N)
- Space
- O(N)
Standard Solution (C++)
SummaryGiven the preorder and inorder traversal sequences of a binary tree, reconstruct and return the root of that tree. Each value is unique, which makes it possible to pinpoint any root's position in the inorder sequence and determine the exact sizes of left and right subtrees.
Approach
- The first element of any preorder subarray is always the current subtree's root.
- A hash map from value to inorder index lets us locate that root in O(1) to split inorder into left and right halves.
- The number of nodes in the left half (call it
leftSize) tells us exactly how many elements in the preorder subarray belong to the left subtree, giving us matching preorder left/right subarrays. - Recurse on both halves; base case is an empty range.
#include <vector>
#include <unordered_map>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *l, TreeNode *r) : val(x), left(l), right(r) {}
};
class Solution {
// Maps each value to its index in the inorder array for O(1) lookup.
unordered_map<int, int> inorderIdx;
// preStart/preEnd: current window in preorder
// inStart/inEnd: current window in inorder
TreeNode* build(const vector<int>& preorder, int preStart, int preEnd,
int inStart, int inEnd) {
if (preStart > preEnd) return nullptr;
int rootVal = preorder[preStart];
int mid = inorderIdx[rootVal]; // root's position in inorder
int leftSize = mid - inStart; // number of nodes in left subtree
TreeNode* root = new TreeNode(rootVal);
root->left = build(preorder,
preStart + 1, preStart + leftSize,
inStart, mid - 1);
root->right = build(preorder,
preStart + leftSize + 1, preEnd,
mid + 1, inEnd);
return root;
}
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = (int)preorder.size();
for (int i = 0; i < n; ++i)
inorderIdx[inorder[i]] = i;
return build(preorder, 0, n - 1, 0, n - 1);
}
}; Time O(n) Space O(n)
A canonical reference solution. Problem statement © LeetCode — see the official link above.
My Solution (C++)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
unordered_map<int, int> umap;
TreeNode* traversal(const vector<int>& preorder, const vector<int>& inorder, int l1, int r1, int l2, int r2) {
if(l1>r1){
return nullptr;
}
int val=preorder[l1];
TreeNode* root=new TreeNode(val);
int m=umap[val]; // idx in inorder
// left tree size: m-l2
int llen=m-l2;
root->left=traversal(preorder, inorder, l1+1, l1+llen, l2, m-1);
root->right=traversal(preorder, inorder, l1+llen+1, r1, m+1, r2);
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int len=preorder.size();
for(int i=0; i<len; ++i){
umap[inorder[i]]=i;
}
return traversal(preorder, inorder, 0, len-1, 0, len-1);
}
};
// Time Complexity: O(N)
// Space Complexity: O(N) Time O(N) Space O(N)
My own solution and notes, as I wrote them.
▶ Run it — editable in-browser playground with a sample driver C++
Your solution plus an auto-generated main() and sample input so Run produces output. The driver and inputs are unverified — edit freely; Reset restores this starting point.
C++ ▶ Runnable Auto-generated driver with sample input — unverified.
Runs in a free public sandbox (Wandbox). Output and timing include network latency; don't paste secrets.