437. 路径总和 III

电玩女神 2023-10-11 18:19 157阅读 0赞

打卡!!!每日一题

今天给大家带来一道深度优先遍历的题目,要知道树的前序遍历就是深度优先遍历,按照这个思路很多题目就会很轻松的解决。

题目描述:437. 路径总和 III

给定一个二叉树的根节点 root ,和一个整数 targetSum ,求该二叉树里节点值之和等于 targetSum 的 路径 的数目。

路径 不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。

题目示例:
在这里插入图片描述

在这里插入图片描述

这道题我只需要穷举就好,思路也很简单,我们只需记住每一个结点的父节点,然后一直向上去找,一直找到根节点为止。

  • 1.保存每一个结点的父节点

    /**

    1. * 子--->父
    2. */
    3. static Map<TreeNode, TreeNode> map = new HashMap<>();
    4. public static void dfs(TreeNode root) {
    5. if (root == null) {
    6. return;
    7. }
    8. if (root.left != null) {
    9. map.put(root.left, root);
    10. }
    11. if (root.right != null) {
    12. map.put(root.right, root);
    13. }
    14. dfs(root.left);
    15. dfs(root.right);
    16. }
  • 2.向上穷举

    while (map.get(t) != null) {

    1. t = map.get(t);
    2. ans += t.val;
    3. if (ans == targetSum) {
    4. count++;
    5. break;
    6. }
    7. }

最终代码如下:

  1. public class 路径总和III_437 {
  2. /**
  3. * 子--->父
  4. */
  5. static Map<TreeNode, TreeNode> map = new HashMap<>();
  6. public static int pathSum(TreeNode root, int targetSum) {
  7. if (root == null) {
  8. return 0;
  9. }
  10. dfs(root);
  11. Queue<TreeNode> queue = new LinkedList<>();
  12. queue.add(root);
  13. int count = 0;
  14. while (!queue.isEmpty()) {
  15. TreeNode t = queue.peek();
  16. long ans = t.val;
  17. if (ans == targetSum) count++;
  18. while (map.get(t) != null) {
  19. t = map.get(t);
  20. ans += t.val;
  21. if (ans == targetSum) {
  22. count++;
  23. break;
  24. }
  25. }
  26. t = queue.poll();
  27. if (t.left != null) {
  28. queue.add(t.left);
  29. }
  30. if (t.right != null) {
  31. queue.add(t.right);
  32. }
  33. }
  34. return count;
  35. }
  36. public static void dfs(TreeNode root) {
  37. if (root == null) {
  38. return;
  39. }
  40. if (root.left != null) {
  41. map.put(root.left, root);
  42. }
  43. if (root.right != null) {
  44. map.put(root.right, root);
  45. }
  46. dfs(root.left);
  47. dfs(root.right);
  48. }
  49. }

我刚开始写的时候ans写的是int类型的,结果一直无法通过最后一个测试用例
在这里插入图片描述

后来我才注意到,虽然树的每一个结点的都是int类型,但是整型超过128之后就无法通过==来进行对比,所以声明为 long或者更高精度的值都可以。

发表评论

表情:
评论列表 (有 0 条评论,157人围观)

还没有评论,来说两句吧...

相关阅读

    相关 437. 路径总和 III

    打卡!!!每日一题 今天给大家带来一道深度优先遍历的题目,要知道树的前序遍历就是深度优先遍历,按照这个思路很多题目就会很轻松的解决。 题目描述:[437. 路径总和 III

    相关 437. 路径总和 III

    > 给定一个二叉树,它的每个结点都存放着一个整数值。 > > 找出路径和等于给定数值的路径总数。 > > 路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是