Leetcode•Jun 30, 2025
Construct Binary Tree from Preorder and Inorder Traversal
Hazrat Ali
Leetcode
Given two integer arrays preorder
and inorder
where preorder
is the preorder traversal of a binary tree and inorder
is the inorder traversal of the same tree, construct and return the binary tree.
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]
Solution
/**
* @param {number[]} preorder
* @param {number[]} inorder
* @return {TreeNode}
*/
const buildTree = (preorder, inorder) => {
const helper = (p1, p2, i1, i2) => {
if (p1 > p2 || i1 > i2) {
return null;
}
const value = preorder[p1];
const index = inorder.indexOf(value);
const count = index - i1;
const root = new TreeNode(value);
root.left = helper(p1 + 1, p1 + count, i1, index - 1);
root.right = helper(p1 + count + 1, p2, index + 1, i2);
return root;
};
return helper(0, preorder.length - 1, 0, inorder.length - 1);
};