Javascript solution using DFS


  • 0
    S
    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @param {number} sum
     * @return {number[][]}
     */
    var pathSum = function(root, sum) {
        if (!root) { return []; }
        
        let res = [];
        helper(root, res, [], 0, sum);
        
        return res;
    };
    
    var helper = function(root, res, path, curSum, sum) {
        path.push(root.val);
        curSum += root.val;
        
        if (root.left === null && root.right === null) {
            if (curSum === sum) { res.push(path.slice()); }
            return;
        }
        
        if (root.left) {
            helper(root.left, res, path, curSum, sum);
            path.pop();
        }
        if (root.right) {
            helper(root.right, res, path, curSum, sum);
            path.pop();
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.