easy dfs java


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

Log in to reply
 

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