/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
bool res = false;
bool hasPathSum(TreeNode* root, int sum) {
// write code here
if (root == NULL)return res;
dfs(root,0, sum);
return res;
}
void dfs(TreeNode* root, int cur, int sum) {
if (root==NULL) {//边界
return;
}
cur=cur+root->val;//前序遍历
if (root->left == NULL && root->right == NULL) {//路径终点
if (cur == sum) {
res = true;
}
return;
}
dfs(root->left, cur, sum);
dfs(root->right, cur, sum);
}
};