Build Binary Tree from Preorder and Inorder Traversal

Preorder gives the next root; index lookup in inorder splits left and right subtree ranges.

Medium
Time O(n) Space O(n)
LeetCode
4 min read
tree dfs divide-and-conquer

Problem#

Given preorder and inorder traversal arrays of a binary tree with unique values, reconstruct and return the tree.

Examples#

  • preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] → tree with root 3.
  • preorder = [-1], inorder = [-1] → single node.

Constraints#

  • 1 <= preorder.length <= 3000. All values are unique.

Approach#

Preorder’s first element is the root. Find its index in inorder — everything left is the left subtree’s inorder, everything right is the right subtree’s inorder. Slice preorder accordingly. Use a hash map for O(1) inorder lookup.

Solution#

Build Binary Tree from Preorder and Inorder Traversal
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
unordered_map<int,int> idx;
for (int i = 0; i < (int)inorder.size(); ++i) idx[inorder[i]] = i;
int p = 0;
function<TreeNode*(int,int)> build = [&](int lo, int hi) -> TreeNode* {
if (lo > hi) return nullptr;
int v = preorder[p++];
TreeNode* node = new TreeNode(v);
int m = idx[v];
node->left = build(lo, m - 1);
node->right = build(m + 1, hi);
return node;
};
return build(0, inorder.size() - 1);
}
};

Editorial#

The preorder cursor p advances exactly n times, and each call does O(1) hash lookup. Building left first matches the preorder consumption order — switching to “right first” would corrupt the cursor.

Complexity#

  • Time: O(n).
  • Space: O(n).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.