/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {number[]} preorder
* @param {number[]} inorder
* @return {TreeNode}
*/
let preorderIdx = 0;
let inroderMap;
var buildTree = function (preorder, inorder) {
preorderIdx = 0;
inorderMap = inorder.reduce((acc, curr, i) => (acc[curr] = i, acc), {});
return construct(preorder, 0, preorder.length - 1);
};
function construct(preorder, left, right) {
if (preorderIdx >= preorder.length) {
return null;
}
if (left > right) {
return null;
}
const value = preorder[preorderIdx++];
const node = new TreeNode(value);
const inorderIdx = inorderMap[value];
node.left = construct(preorder, left, inorderIdx - 1);
node.right = construct(preorder, inorderIdx + 1, right);
return node;
}