首页 > 其他 > 详细

LeetCode -- Path Sum

时间:2015-10-14 01:37:46      阅读:87      评论:0      收藏:0      [点我收藏+]
题目描述:


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.




就是从根到叶子,判断是否存在和为sum的路径。


思路:


一道典型的DFS题,遍历时累加当前节点数即可。


实现代码:


public bool HasPathSum(TreeNode root, int sum) {
        Find(root, 0, sum);
        return found;
    }
    
    private bool found = false;
    
    private void Find(TreeNode node, int sum, int target){
        if(found || node == null){
            return;
        }
        if(node.left == null && node.right == null){
		if(sum + node.val == target){
            		found = true;
        	}
	}
        
        
        Find(node.left, sum + node.val, target);
        Find(node.right, sum + node.val, target);
    }


版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode -- Path Sum

原文:http://blog.csdn.net/lan_liang/article/details/49108383

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