3ms accepted java solution


  • 0
    W

    public class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
    List<List<Integer>> result = new ArrayList<List<Integer>>();
    if(root==null){
    return result;
    }
    getPath(result, new ArrayList<Integer>(), root,sum);
    return result;

    }
    
    private void getPath(List<List<Integer>> result, ArrayList<Integer> path, TreeNode root, int sum){
        
        if(root!=null){
            path.add(root.val);
            if(sum-root.val==0&&root.left==null&&root.right==null){
                result.add(new ArrayList<Integer>(path));
            }else{
                getPath(result, path, root.left,  sum-root.val);
                getPath(result, path, root.right, sum-root.val);
            }
            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.