LeetCode solutions

106. Construct Binary Tree from Inorder and Postorder Traversal

My accepted JavaScript solution to LeetCode problem 106, Construct Binary Tree from Inorder and Postorder Traversal, running in 3ms.

  • Difficulty: Medium
  • JavaScript
  • Runtime 3ms
  • Memory 58.4MB

Read the problem on LeetCode View on GitHub

JavaScript

Accepted on LeetCode — runtime 3ms, memory 58.4MB, accepted 2025-12-24.

javascript
/**
 * @param {number[]} inorder
 * @param {number[]} postorder
 * @return {TreeNode}
 */
var buildTree = function(inorder, postorder) {
    const map = new Map();
    inorder.forEach((val, idx) => map.set(val, idx));
    
    let postIdx = postorder.length - 1;
    
    const build = (left, right) => {
        if (left > right) return null;
        
        const rootVal = postorder[postIdx--];
        const root = new TreeNode(rootVal);
        const mid = map.get(rootVal);
        
        // Build right subtree first (postorder goes right to left from end)
        root.right = build(mid + 1, right);
        root.left = build(left, mid - 1);
        
        return root;
    };
    
    return build(0, inorder.length - 1);
};

Source