LeetCode 112. Path Sum

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,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

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

java代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private boolean stop = false;

    public boolean hasPathSum(TreeNode root, int sum) {
        calculate(root, 0, sum);
        return stop;
    }

    private void calculate(TreeNode node, int cur, int sum) {
        if (!stop && node != null) {
            if (node.left == null && node.right == null && (node.val + cur == sum)) {
                stop = true;
            }
            if (node.left != null) {
                calculate(node.left, cur+node.val, sum);
            }
            if (node.right != null) {
                calculate(node.right, cur+node.val, sum);
            }

        }

    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,775评论 0 33
  • 图/网络 时光正好 从前车马很远,一生只够爱一个人 现在,大多数人都奉行快餐主义,借用“大牛教授”一句话,现在能做...
    钗说阅读 322评论 3 0
  • 01 作为一名业余摄影爱好者,远离了商业的气息,没有投稿比赛的压力,我按下快门的动机更为简单,也更为坚定,即在我开...
    一轮明月亘古今阅读 1,981评论 0 7
  • 老朱改名了,終於顯示了與眾不同也充分說明成大事者,心胸,能力,眼光從一開始就鉴定其未來,而眼光正是在未表現其才能或...
    萌貓咪阅读 135评论 0 0
  • 在小学,我有3个很要好的朋友:一个叫马精梅,一个叫王旭婷,另一个则是周怡扬。 不知道为什么,到了六年级...
    小黎黎黎阅读 618评论 6 1