My AC Java Solution


  • 0
    Y
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        private List<List<Integer>> result = new ArrayList<>();
    
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            help(root, new ArrayList<Integer>(), sum);
            return result;
        }
    
        private void help(TreeNode root, List<Integer> list, int sum) {
            if (root == null) {
                return;
            }
            list.add(root.val);
            if (root.left == null && root.right == null && sum - root.val == 0) {
                List listOther = new ArrayList(list);
                result.add(listOther);
            }
            help(root.left, list, sum - root.val);
            help(root.right, list, sum - root.val);
            list.remove(list.size() - 1);
        }
    }
    

Log in to reply
 

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