首页 > 其他 > 详细

[LeetCode]112 Path Sum

时间:2015-01-06 15:45:06      阅读:143      评论:0      收藏:0      [点我收藏+]

https://oj.leetcode.com/problems/path-sum/

http://blog.csdn.net/linhuanmars/article/details/23654413

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root == null)
            return false;

        return check(root, sum, 0);
    }
    
    private boolean check(TreeNode node, int target, int sumSoFar)
    {
        sumSoFar += node.val;
        
        // A leaf
        if (node.left == null && node.right == null)
        {
            return sumSoFar == target;
        }
        
        boolean r = false;
        if (node.left != null)
            r |= check(node.left, target, sumSoFar);
    
        if (node.right != null)
            r |= check(node.right, target, sumSoFar);
            
        return r;
    }
}


[LeetCode]112 Path Sum

原文:http://7371901.blog.51cto.com/7361901/1599715

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!