AC java solution


  • 0
    U
    public class Solution {// path sum from the leaf to bot;
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res= new ArrayList<List<Integer>>();
        List<Integer> each= new ArrayList<Integer>();
        dfs(root,res,each,sum);
        return res;
    }
    private void dfs(TreeNode root, List<List<Integer>> res, List<Integer> each,int target){
        if(root==null)
            return;
        each.add(root.val);
        int remain=target-root.val;
        // remember base case doeset have to be the first part code of dfs;
        if(remain==0&&root.left==null&&root.right==null){
            res.add(new ArrayList(each));
            each.remove(each.size()-1);
            return;
        }
       
        dfs(root.left,res,each,remain);
        dfs(root.right,res,each,remain);
        
        each.remove(each.size()-1);
    }
    

    }


  • 0
    C

    I know your code is right,my code is nearly the same as yours,except the last line,each.remove(each,size()-1),i don't have this,and i got a time limited exception,can you tell me why?


Log in to reply
 

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