JavaScript DFS Solution


  • 0
    var pathSum = function(root, sum) {
        if(!root) return [];
        var result = [];
        function path(root, str, amount){
            amount += root.val;
            if(!root.left && !root.right){
                str += root.val;            
                if(amount === sum) result.push(str.split(" ").map(Number));
            }
            if(root.left) path(root.left, str + root.val + " ", amount);
            if(root.right) path(root.right, str + root.val + " ", amount);
        }
        path(root, "", 0);
        return result;
    };

Log in to reply
 

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