前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LeetCode笔记:112. Path Sum

LeetCode笔记:112. Path Sum

作者头像
Cloudox
发布2021-11-23 14:18:13
1250
发布2021-11-23 14:18:13
举报
文章被收录于专栏:月亮与二进制月亮与二进制

问题:

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree and sum = 22,

image.png return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

大意:

给出一个二叉树和一个值,判断树是否有从根节点到叶子节点的路径让每个节点的值加起来等于给出的值。 例子: 给出下面的二叉树以及 sum = 22,

image.png 返回true,因为存在根节点到叶子节点的路径 5->4->11->2 加起来的和为22。

思路:

这个因为只需要判断有没有路径满足,也就是说只需要找到一条即可,那么采用深度优先遍历比较好,用递归来实现。

每次判断当前路径的累加和是否等于目标值了,如果等于,因为题目要求从根节点到叶子节点,所以还要判断是否已经到叶子节点了,这个对有无左右子节点判断就可以了。

如果还不等于,那么就继续判断走左子节点或者走右子节点有没有等于。

要注意的是题目并没说节点值都是正数,我之前对当前的累加和是否已经大于了目标值来希望减少一些多余的运算,属于自作聪明了,对于负数目标值来说,就完全错误了。

代码(Java):

代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        return canSum(root, sum, 0);
    }
    
    public boolean canSum(TreeNode root, int sum, int nowSum) {
        if (root == null) return false;
        
        nowSum = nowSum + root.val;
        System.out.println(nowSum);
        if (nowSum == sum && root.left == null && root.right == null) return true;
        else return canSum(root.left, sum, nowSum) || canSum(root.right, sum, nowSum);
    }
}

合集:https://github.com/Cloudox/LeetCode-Record

查看作者首页

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2017/11/22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 问题:
  • 大意:
  • 思路:
  • 代码(Java):
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档