题解 | #二叉树中和为某一值的路径(一)#
二叉树中和为某一值的路径(一)
http://www.nowcoder.com/practice/508378c0823c423baa723ce448cbfd0c
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
bool result = false;
void dfs(TreeNode* root, long int sum,long int ans){
if(root){
dfs(root->left,sum,ans + root->val);
dfs(root->right,sum,ans + root->val);
if(root->left == NULL && root->right == NULL && ans + root->val == sum)
result = true;
}
}
bool hasPathSum(TreeNode* root, long int sum) {
if(root == NULL)
return false;
dfs(root,sum,0);
return result;
}
};