还有iterative的方法,看起来很麻烦好像要用多个栈,回头可以学习一下
/**
* 自己的代码,recursive
* Runtime: 1 ms, faster than 99.94%
* Memory Usage: 39.2 MB, less than 78.25%
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) // 是空节点
return res;
targetSum -= root.val;
if (root.left == null && root.right == null) { // 是叶子节点
if (targetSum == 0) {
List curr = new ArrayList<>();
curr.add(root.val);
res.add(curr);
}
return res;
}
res.addAll(pathSum(root.left, targetSum)); // 获取左子树所有有效路径
res.addAll(pathSum(root.right, targetSum)); // 获取右子树所有有效路径
for (List l : res)
l.add(0, root.val); // 将当前节点的val加到每条路径中(注意要加在头部,即index为0)
return res;
}
}
/**
* 用helper的recursive方法
* 要注意对于所有递归共享的地址,每次修改都要用完了后改回去
* Runtime: 1 ms, faster than 99.94%
* Memory Usage: 38.9 MB, less than 95.52%
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> res = new ArrayList<>();
helper(root, targetSum, res, new ArrayList<>());
return res;
}
private void helper(TreeNode root, int targetSum, List<List<Integer>> res, List<Integer> path) {
if (root == null)
return;
targetSum -= root.val;
path.add(root.val);
if (root.left == null && root.right == null && targetSum == 0)
res.add(new ArrayList(path)); // 不能直接add(path),因为path被所有递归共用,会不断被修改,要深拷贝一个path
helper(root.left, targetSum, res, path);
helper(root.right, targetSum, res, path);
path.remove(path.size() - 1); // 所有递归里共用同一个path地址,所以每次修改path之后必须改回去
}
}