您的位置:首页 > 编程语言 > C语言/C++

【leetcode c++】 112 Path Sum

2015-07-31 23:27 477 查看
Path Sum

 

Given a binary tree and a sum, determine ifthe tree has a root-to-leaf path such that adding upall the values along the path equals the given sum.

For example:

Given the below binary tree and sum = 22,



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

 

我依然使用递归的方法去遍历,但是,考虑一下,这题有情况是在未全部遍历的情况下找到一条路径了,则后面的遍历就不需要了,我们可以考虑避免一些多余的遍历。

 

考虑递归的传参,首先要传一个sum,也就是我们要找的和,其次要传一个整型的引用,来表示当前节点为止的和,然后,到达叶子节点之后判断这两个和是否相等。最后,在递归函数的末尾还要减掉当前节点的值。

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
int preSum = 0;
bool hasRes = false;
Lv(root, sum, preSum, hasRes);
return hasRes;
}

void Lv(TreeNode* root,int sum, int& preSum, bool& hasRes) {
if(hasRes) return;
if(NULL == root) return;
preSum += root->val;
if(!root->left && !root->right)
{
if(sum == preSum)
{
hasRes = true;
return;
}
}

Lv(root->left, sum, preSum, hasRes);
Lv(root->right, sum, preSum, hasRes);
preSum -= root->val;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode