题目:
代码:
/**
* 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:
int flag=0,num;
void dfs(TreeNode* root, int sum,int num) //num为当前和
{
if(flag) return; //flag标记后一直reuturn就行,不用判断了
if(root->left==NULL && root->right==NULL) //叶子
{
if(num==sum) flag=1; //找到相同的,标记flag
return;
}
if(root->left) dfs(root->left,sum,num+root->left->val); //左子树
if(root->right) dfs(root->right,sum,num+root->right->val);//右子树
}
bool hasPathSum(TreeNode* root, int sum) {
if(root==NULL) return false; //空树
num=root->val; //根的值
dfs(root,sum,num);
return flag;
}
};