码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode -- Path Sum

时间:2015-10-14 01:40:19      阅读:135      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!