Share my JAVA solution, 6ms


  • 0
    H
    public class Solution {
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> res=new ArrayList<>();
            if(root!=null) helper(res, root, sum, new ArrayList<>());
            return res;
        }
        
        public void helper(List<List<Integer>> res, TreeNode root, int sum, List<Integer> list){
            List<Integer> curr=new ArrayList<>(list);
            curr.add(root.val);
            if(root.left==null && root.right==null){
                if(root.val==sum){
                    res.add(curr);
                }
            }else{
                if(root.left!=null) helper(res, root.left, sum-root.val, curr);
                if(root.right!=null) helper(res, root.right, sum-root.val, curr);
            }
            return;
        }
    }
    

Log in to reply
 

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