Clean, very short and efficient Java Solution

  • 0

    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;
        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);
        return result;


Log in to reply

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