easy DFS java solution


  • 0
    G
    public class Solution {
        public List<List<Integer>> pathSum(TreeNode root, int sum) {
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            List<Integer> as = new ArrayList<Integer>();
            helper(res,as,root,sum);
            return res;
            
            
        }
        
        public void helper(List<List<Integer>> res,List<Integer> as,TreeNode root, int sum ) 
        {
            
            if(root==null)
            {
                return;
            }
            
            as.add(root.val);
            
            if(root.val==sum && root.left==null && root.right==null)
            {
                res.add(new ArrayList(as));
            }
            
            helper(res,as,root.left,sum-root.val);
            
            helper(res,as,root.right,sum-root.val);
            as.remove(as.size()-1);
            //as.remove(as.size()-1);
            
        }
    }

Log in to reply
 

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