Clean, very short and efficient Java Solution


  • 0
    K

    public class Solution {

    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        return collectSum(root, new Stack<>(), sum, new ArrayList<>());
    }
    
    private List<List<Integer>> collectSum(TreeNode node, Stack<Integer> currentPath, int sum, List<List<Integer>> result) {
        if (node == null) return result;
        currentPath.push(node.val);
        if (node.left == null && node.right == null && sum == node.val) result.add(new ArrayList(currentPath)); 
        collectSum(node.left,  currentPath, sum - node.val, result);
        collectSum(node.right, currentPath, sum - node.val, result);
        currentPath.pop();
        return result;
    }
    

    }


Log in to reply
 

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