Simple clean Java, recursive


  • 2
    J
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        pathSum(ans, path, root, sum);
        return ans;
    }
    
    private void pathSum(List<List<Integer>> ans, List<Integer> path,
    		TreeNode root, int sum) {
    	if (root == null)
    		return;
    	List<Integer> newPath = new ArrayList<>(path);
    	newPath.add(root.val);
    	if (root.left == null && root.right == null && root.val == sum) {
    		ans.add(newPath);
    		return;
    	}
    	pathSum(ans, newPath, root.left, sum - root.val);
    	pathSum(ans, newPath, root.right, sum - root.val);
    }

  • 0
    Y
    This post is deleted!

Log in to reply
 

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