Construct Binary Tree from Preorder and Inorder Traversal
Difficulty: Medium · Pattern: Trees & BST · LeetCode #105
Given two integer arrays preorder and inorder, the preorder and inorder traversals of the same binary tree with unique values, build and return the tree.
Examples
text
preorder = [3,9,20,15,7], inorder = [9,3,15,20,7] → [3,9,20,null,null,15,7]
preorder = [-1], inorder = [-1] → [-1]Hints
- The first element of preorder is always the root.
- Find that root in inorder: everything to its left is the left subtree, everything to its right is the right subtree. The counts tell you how to split preorder too.
Approach
text
preorder: [ root | ---- left (k) ---- | ---- right ---- ]
inorder: [ ---- left (k) ---- | root | ---- right ---- ]- Build a hash map
value → inorder indexso each lookup is O(1). Without it, the scan makes the build O(n²). - Keep a global pointer
preinto preorder. Recurse with an inorder window[lo, hi]:- If
lo > hi, return null. root = preorder[pre++],mid = idx[root].- Build the left subtree from
[lo, mid-1]first, then the right subtree from[mid+1, hi]. Preorder lists the whole left subtree before the right one, so this order keeps the pointer in sync.
- If
Unique values are what make the tree uniquely determined. With duplicates the reconstruction can be ambiguous.
Complexity
Time: O(n). Space: O(n) for the map plus O(h) recursion.
Python solution
def buildTree(preorder, inorder):
idx = {v: i for i, v in enumerate(inorder)}
pre = 0
def build(lo, hi):
nonlocal pre
if lo > hi:
return None
root = TreeNode(preorder[pre])
pre += 1
mid = idx[root.val]
root.left = build(lo, mid - 1)
root.right = build(mid + 1, hi)
return root
return build(0, len(inorder) - 1)JavaScript solution
function buildTree(preorder, inorder) {
const idx = new Map(inorder.map((v, i) => [v, i]));
let pre = 0;
const build = (lo, hi) => {
if (lo > hi) return null;
const root = new TreeNode(preorder[pre++]);
const mid = idx.get(root.val);
root.left = build(lo, mid - 1);
root.right = build(mid + 1, hi);
return root;
};
return build(0, inorder.length - 1);
}