Simplest solution in java to avoid appending to the temp list


  • 0
    P
    public class Solution {
        List<List<Integer>>res=new ArrayList<>();
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
             List<Integer>tmp=new ArrayList<>();
             pathSum(root,0,sum,tmp);  
             return res;
             
        }
        
        public void pathSum(TreeNode root, int sum,int target,List<Integer> tmp){
            if (root==null)return;
            sum+=root.val;
            tmp.add(root.val);
            if(root.left==null&&root.right==null&&sum==target)
            res.add(tmp);     
            if(root.left!=null){
              pathSum(root.left,sum,target,new ArrayList(tmp));  
            }
            if(root.right!=null){
                 pathSum(root.right,sum,target,new ArrayList(tmp));  
            }
        }}```

Log in to reply
 

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