[Leetcode][第112题][JAVA][路径总和][递归][队列]

239 篇文章 1 订阅
【问题描述】[中等]

在这里插入图片描述

【解答思路】
1. 递归

在这里插入图片描述
时间复杂度:O(N) 空间复杂度:O(H)
在这里插入图片描述
从根节点开始,每当遇到一个节点的时候,从目标值里扣除节点值,一直到叶子节点判断目标值是不是被扣完。

class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }
        if (root.left == null && root.right == null) {
        // return sum-root.val==0;
            return sum == root.val;
        }
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}

声明一个变量记录已经经过的节点的值之和,每经过一个节点就加上这个节点的值,在叶子节点判断变量值是否为目标值。

 public boolean hasPathSum(TreeNode root, int sum) {
      return  helper(root,0,sum);
    }
    public boolean helper(TreeNode root,int cur,int sum)
    {
      if(root==null)
          return false;
        cur=cur+root.val;
        if(root.left==null&&root.right==null)
        {
            return cur==sum;
        }else
        {
            return helper(root.left,cur,sum)|| helper(root.right,cur,sum);
        }
    }
2. 广度优先搜索

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
时间复杂度:O(N) 空间复杂度:O(N)
在这里插入图片描述

class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null) {
            return false;
        }
        Queue<TreeNode> queNode = new LinkedList<TreeNode>();
        Queue<Integer> queVal = new LinkedList<Integer>();
        queNode.offer(root);
        queVal.offer(root.val);
        while (!queNode.isEmpty()) {
            TreeNode now = queNode.poll();
            int temp = queVal.poll();
            if (now.left == null && now.right == null) {
                if (temp == sum) {
                    return true;
                }
                continue;
            }
            if (now.left != null) {
                queNode.offer(now.left);
                queVal.offer(now.left.val + temp);
            }
            if (now.right != null) {
                queNode.offer(now.right);
                queVal.offer(now.right.val + temp);
            }
        }
        return false;
    }
}

【总结】
1.注意事项

在这里插入图片描述

2.数的递归

树的递归题目是非常有套路可循的,因为树有两个分支,所以在递归里也有两个分支,一般是通过 递归 A(||,&&)递归 B 来实现分支的。只要明白了这一点,递归函数就不会很难设计。

3.巧妙使用了两个队列 一个队列保存遍历节点 另一节点保存和

参考链接:https://leetcode-cn.com/problems/path-sum/solution/lu-jing-zong-he-by-leetcode-solution/

参考链接:https://leetcode-cn.com/problems/path-sum/solution/lu-jing-zong-he-jie-da-by-commonheart/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值