# 112. 路径总和

5
/ \
4   8
/   / \
11  13  4
/  \      \
7    2      1

/**
* 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:
bool dfs(TreeNode* root, int thisSum, int sum)
{
if(!root) return false;
thisSum += root->val;
if(thisSum == sum)
{
if(!root->left && !root->right) return true;
// else return false;
}
// else if(thisSum > sum) return false;
return dfs(root->left, thisSum, sum) || dfs(root->right, thisSum, sum);
}
bool hasPathSum(TreeNode* root, int sum) {
return dfs(root, 0, sum);
}
};

/**
* 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:
bool dfs(TreeNode* root, int thisSum, int sum)
{
if(!root) return false;
thisSum += root->val;
if(!root->left && !root->right) return thisSum == sum;
return dfs(root->left, thisSum, sum) || dfs(root->right, thisSum, sum);
}
bool hasPathSum(TreeNode* root, int sum) {
return dfs(root, 0, sum);
}
};

©️2019 CSDN 皮肤主题: 深蓝海洋 设计师: CSDN官方博客