Java solution, Hope you find it helpful


  • 0
    M
    public class Solution {
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> res = new ArrayList<>();
            if(root==null)
                return res;
            else{ 
                List<Integer> subres = new ArrayList<Integer>();
                pathSum_m(root,sum, res, subres);
            }
            return res;
        }
        
        public void pathSum_m(TreeNode root, int sum, List<List<Integer>> res, List<Integer> subres) {
            
            if(root==null){
            	return;
            }
                
            else{
                subres.add(root.val);
                int subsum = sum-root.val;
                if(subsum==0 && root.left==null && root.right==null){
                    List<Integer> temp = new ArrayList<Integer>();
                	temp.addAll(subres);
                	res.add(temp);
                    //subres.remove(subres.size()-1);
                    
                }
                
                if(root.left!=null){
                    pathSum_m(root.left, subsum, res, subres);
    
                }
                
                
                if(root.right!=null){
                    if(subres.size()==0)
                    	subres.add(root.val);
                    pathSum_m(root.right, subsum, res, subres);
    
                }
                if(subres.size()!=0)
                	subres.remove(subres.size()-1);
                
    
                
            }
        
        }
    }
    

Log in to reply
 

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