LeetCode solutions

113. Path Sum II

My accepted JavaScript solution to LeetCode problem 113, Path Sum II, running in 1ms.

  • Difficulty: Medium
  • JavaScript
  • Runtime 1ms
  • Memory 58.6MB

Read the problem on LeetCode View on GitHub

JavaScript

Accepted on LeetCode — runtime 1ms, memory 58.6MB, accepted 2025-12-24.

javascript
/**
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {number[][]}
 */
var pathSum = function(root, targetSum) {
    const result = [];
    
    const dfs = (node, remaining, path) => {
        if (!node) return;
        
        path.push(node.val);
        
        // Check if leaf node with correct sum
        if (!node.left && !node.right && remaining === node.val) {
            result.push([...path]);
        }
        
        dfs(node.left, remaining - node.val, path);
        dfs(node.right, remaining - node.val, path);
        
        path.pop();
    };
    
    dfs(root, targetSum, []);
    return result;
};

Source