class Solution {
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
bool flag = false; // 结果返回
void dfs(TreeNode *root,int sum, int total){
if(root == nullptr || flag == true){
return;
}
total += root->val;
if(root->left == nullptr && root->right == nullptr){
if(total == sum){
flag = true;
}
}else{
dfs(root->left,sum,total);
dfs(root->right,sum,total);
}
}
bool hasPathSum(TreeNode* root, int sum) {
// write code here
dfs(root,sum,0);
return flag;
}
};