2021/05/04
DFS
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> res = new ArrayList<>();
pathSum_0(root, targetSum, new ArrayList<>(), res);
return res;
}
public void pathSum_0(TreeNode root, int targetSum, List<Integer> cur, List<List<Integer>> res) {
if (root == null) return;
cur.add(root.val);
if (root.left == null && root.right == null && targetSum == root.val) { // 到根节点了
res.add(new ArrayList<>(cur));
} else { // 没到根节点
pathSum_0(root.left, targetSum - root.val, cur, res);
pathSum_0(root.right, targetSum - root.val, cur, res);
}
cur.remove(cur.size() - 1);
}
}
2019年写的答案
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new LinkedList<>();
if (root == null) return res;
if (root.left == null && root.right == null) {
if (root.val == sum) {
List<Integer> r = new LinkedList<>();
r.add(root.val);
res.add(r);
}
return res;
}
List<List<Integer>> leftRes = pathSum(root.left, sum - root.val);
List<List<Integer>> rightRes = pathSum(root.right, sum - root.val);
leftRes.addAll(rightRes);
for (List<Integer> path: leftRes) {
path.add(0, root.val);
res.add(path);
}
return res;
}
}