领扣LintCode算法问题答案-1358. 路径和

    科技2022-07-13  134

    领扣LintCode算法问题答案-1358. 路径和

    目录

    1358. 路径和描述样例 1:样例 2: 题解鸣谢

    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; } }

    原题链接点这里

    鸣谢

    非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。 欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

    Processed: 0.015, SQL: 8