Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save RP-3/70e00e609eb06ebca74c9614f4456c8d to your computer and use it in GitHub Desktop.

Select an option

Save RP-3/70e00e609eb06ebca74c9614f4456c8d to your computer and use it in GitHub Desktop.
/**
* 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[]} inorder
* @param {number[]} postorder
* @return {TreeNode}
*/
var buildTree = function(inorder, postorder) {
if(!postorder.length) return null;
const idx = {};
inorder.forEach((v, i) => idx[v] = i);
const build = (l, r) => {
if(l > r) return null;
const node = new TreeNode(postorder.pop());
if(l === r) return node;
const index = idx[node.val];
node.right = build(index+1, r);
node.left = build(l, index-1);
return node;
};
return build(0, inorder.length-1);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment