简单,注意变量的初始化!
/**
* Definition for binary tree
* 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) {
if (root == NULL)
return false;
return dfs(root, sum, 0);
}
bool dfs(TreeNode *root, int sum, int cur_sum) {
cur_sum += root->val;
if (root->left == NULL && root->right == NULL) {
if (cur_sum == sum)
return true;
return false;
}
bool l = false, r = false;
if(root->left != NULL) {
l = dfs(root->left, sum, cur_sum);
}
if(root->right != NULL) {
r = dfs(root->right, sum, cur_sum);
}
return l || r;
}
};
http://oj.leetcode.com/problems/path-sum/