剑指 Offer 34. 二叉树中和为某一值的路径

image.png
剑指 Offer 34. 二叉树中和为某一值的路径 - 图2

图片转自 https://leetcode-cn.com/leetbook/read/illustration-of-algorithm/5dc8rr/

递归

化加法为减法,如果 target 与路径上的所有值相关之后为 0,说明路径符合要求
image.png

  1. public class Solution {
  2. // 存储结果
  3. private List<List<Integer>> res = new LinkedList<>();
  4. // 临时存放路径
  5. private LinkedList<Integer> path = new LinkedList<>();
  6. public List<List<Integer>> pathSum(TreeNode root, int sum) {
  7. // 深度优先搜索路径
  8. recursion(root, sum);
  9. return this.res;
  10. }
  11. public void recursion(TreeNode node, int target) {
  12. // 如果为空,说明路径不符合要求。直接返回
  13. if (node == null) return;
  14. // 将节点值加入路径中
  15. path.add(node.val);
  16. // 减去节点的值
  17. target -= node.val;
  18. // 如果是叶子节点 && target 为 0 说明路径符合
  19. if (node.left == null && node.right == null && target == 0) {
  20. // 将路径拷贝一份放入结果集
  21. res.add(new LinkedList<>(path));
  22. }
  23. // 分别递归搜索左子树和右子树
  24. recursion(node.left, target);
  25. recursion(node.right, target);
  26. // 回溯时要删除路径的最后一个值
  27. path.removeLast();
  28. }
  29. }