领扣LintCode算法问题答案-1358. 路径和
发布日期:2021-06-30 17:10:54
浏览次数:2
分类:技术文章
本文共 1481 字,大约阅读时间需要 4 分钟。
领扣LintCode算法问题答案-1358. 路径和
目录
1358. 路径和
描述
给定二叉树和求和,确定树是否具有根到叶路径,使得沿路径的所有值相加等于给定的总和。
- 叶子是没有孩子的节点。
样例 1:
输入:tree = [5,4,8,11,#,13,4,7,2,#,#,#,#,#,1], sum = 22输出: true解释: 所给二叉树如下 5 / \ 4 8 / / \ 11 13 4 / \ \7 2 1返回true,因为有路径5->4->11->2,总和恰为22
样例 2:
输入:tree = [5,4,8], sum =18 输出: false
题解
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */public class Solution { /** * @param root: the tree * @param sum: the sum * @return: if the tree has a root-to-leaf path */ public boolean pathSum(TreeNode root, int sum) { // Write your code here. if (root == null) { return false; } sum = sum - root.val; if (root.left == null && root.right == null) { return sum == 0; } if (sum <= 0) { return false; } if (root.left != null) { boolean exists = pathSum(root.left, sum); if (exists) { return true; } } if (root.right != null) { boolean exists = pathSum(root.right, sum); if (exists) { return true; } } return false; }}
鸣谢
非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。
欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。
转载地址:https://le-yi.blog.csdn.net/article/details/108915998 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月17日 11时33分34秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
操作系统实验之生产者和消费者程序
2019-04-30
操作系统实验之猴子过桥问题的模拟程序
2019-04-30
POJ - 3067 Japan (树状数组 思维)
2019-04-30
POJ - 2352 Stars (树状数组 入门题)
2019-04-30
HDU - 1166 敌兵布阵 (树状数组模板题/线段树模板题)
2019-04-30
CodeForces - 761C Dasha and Password (思维 暴力)
2019-04-30
POJ - 2481 Cows (树状数组 入门题)
2019-04-30
ACM-ICPC 2018 焦作赛区网络预赛 I. Save the Room
2019-04-30
CodeForces - 987C Three displays (暴力/dp)
2019-04-30
计蒜客 NAIPC 2016 F. Mountain Scenes(dp)
2019-04-30
牛客国庆集训派对Day4——I 连通块计数(思维)
2019-04-30
牛客国庆集训派对Day4——G 区间权值(找规律,双重前缀和)
2019-04-30
牛客国庆集训派对Day5——L 数论之神(找规律/数论)
2019-04-30
CodeForces - 629B Far Relative’s Problem(模拟)
2019-04-30
CodeForces - 1059B Forgery (思维)
2019-04-30
CodeForces - 456C Boredom (dp)
2019-04-30