3ms JAVA solution


  • 0
    L
    public class Solution {
    List<List<Integer>> res = new ArrayList<List<Integer>>();
    int sum;
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        this.sum = sum;
        List<Integer> path = new ArrayList<Integer>();
        if(root == null) return res;
        dfs(root, 0, path);
        return res;
    }
    private void dfs(TreeNode current, int curSum, List<Integer> path){
        path.add(current.val);
        curSum += current.val;
        if(current.left == null && current.right == null){
            if(curSum == sum) {
                List<Integer> list = new ArrayList<Integer>(path);
                res.add(list);
            }
        }
        if(current.left!=null){
            dfs(current.left, curSum, path);
        }
        if(current.right!=null){
            dfs(current.right, curSum, path);
        }
        path.remove(path.size()-1);
    }
    

    }


Log in to reply
 

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