题目描述

image.png

解题思路

典型的路径问题,分多条路径和一条路径,也就是返回值不同。
具体链接🔗

  1. class Solution {
  2. // 方法一
  3. /*public List<List<Integer>> pathSum(TreeNode root, int target) {
  4. if (root == null) {
  5. return res;
  6. }
  7. int count = target - root.val;
  8. dfs(root, path, count);
  9. return res;
  10. }
  11. List<List<Integer>> res = new ArrayList<>();
  12. LinkedList<Integer> path = new LinkedList<>();
  13. public void dfs(TreeNode root, LinkedList<Integer> path, int count) {
  14. path.add(root.val);
  15. if (root.left == null && root.right == null) {
  16. if (count == 0) {
  17. res.add(new LinkedList<>(path));
  18. }
  19. return;
  20. }
  21. if (root.left != null) {
  22. count -= root.left.val;
  23. dfs(root.left, path, count);
  24. count += root.left.val; // 回溯
  25. path.removeLast();
  26. }
  27. if (root.right != null) {
  28. count -= root.right.val;
  29. dfs(root.right, path, count);
  30. count += root.right.val; // 回溯
  31. path.removeLast();
  32. }
  33. return;
  34. }*/
  35. // 方法二
  36. LinkedList<List<Integer>> res = new LinkedList<>();
  37. LinkedList<Integer> path = new LinkedList<>();
  38. public List<List<Integer>> pathSum(TreeNode root, int target) {
  39. recur(root, target);
  40. return res;
  41. }
  42. public void recur(TreeNode root, int tar) {
  43. if (root == null) {
  44. return;
  45. }
  46. path.add(root.val);
  47. tar -= root.val;
  48. // 注意判断左右孩子
  49. if (tar == 0 && root.left == null && root.right == null) {
  50. res.add(new LinkedList(path));
  51. }
  52. recur(root.left, tar);
  53. recur(root.right, tar);
  54. path.removeLast();
  55. }
  56. }