Java solution with recursive, check " sum - root.val" in each recursion.


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

    }


Log in to reply
 

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