DFS求解
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
private:
int res = false;
int cur_sum = 0;
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
bool hasPathSum(TreeNode* root, int sum) {
// write code here
dfs(root, sum);
return res;
}
void dfs(TreeNode* root, int sum){
if(root == nullptr){
return;
}
if(res){
return;
}
cur_sum += root->val;
if(cur_sum == sum && root->left == nullptr && root->right == nullptr){
res = true;
return;
}
dfs(root->left, sum);
dfs(root->right, sum);
cur_sum -= root->val;
}
};