Given the preorder and inorder traversals of a binary tree with unique values, rebuild and return the tree.
The next pre-order value is always the root of the current subtree. Its position in the inorder array splits the remaining values into left and right subtrees. A value → index map makes that lookup O(1).
1function buildTree(preorder: number[], inorder: number[]): TreeNode | null {2const idx = new Map(inorder.map((v, i) => [v, i]));3let p = 0;4function go(lo: number, hi: number): TreeNode | null {5if (lo > hi) return null;6const node = new TreeNode(preorder[p++]);7const mid = idx.get(node.val)!;8node.left = go(lo, mid - 1);9node.right = go(mid + 1, hi);10return node;11}12return go(0, inorder.length - 1);13}
Next pre-order value 3 is the root of inorder[0..4].
Space: play/pause · ←/→: step