Simple AC solution Java


  • 0
    A
    public class Solution {
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> res = new ArrayList<>();
            List<Integer> tmplist = new ArrayList<Integer>();
            int count = 0;
            if(root==null)return res;
            find(count,root,tmplist,sum,res);
            return res;
        }
        
        public void find(int count, TreeNode root, List<Integer> list,int sum,List<List<Integer>> res){
            if(root==null)return;
            if((root.val + count == sum)&&(root.left==null&&root.right==null)){
                count+=root.val;
                List<Integer> newlist = new ArrayList<>();
                newlist.addAll(list);
                newlist.add(root.val);
                res.add(newlist);
                return;
            }else{
                count+=root.val;
                List<Integer> newlist = new ArrayList<>();
                newlist.addAll(list);
                newlist.add(root.val);
                find(count,root.left,newlist,sum,res);
                find(count,root.right,newlist,sum,res);
                return;
            }
        }
    }
    

    Have fun;)


Log in to reply
 

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