领扣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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:领扣LintCode算法问题答案-1359. 有序数组转换为二叉搜索树
下一篇:领扣LintCode算法问题答案-1355. 杨辉三角

发表评论

最新留言

哈哈,博客排版真的漂亮呢~
[***.90.31.176]2024年04月17日 11时33分34秒

关于作者

    喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!

推荐文章