//本题用深度优先遍历的方法比较简单
//每次到叶子节点时比较一下是否等于sum
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
bool hasPathSum(TreeNode* root, int sum) {
// write code here
if(root==NULL)//空树直接返回false
return false;
int res=0;
res+=root->val;
if(root->right==NULL&&root->left==NULL&&res==sum)
return true;
bool leftData=hasPathSum(root->left, sum-res);
bool rightData=hasPathSum(root->right, sum-res);
if(leftData==true||rightData==true)
return true;
else return false;
}
};
//每次到叶子节点时比较一下是否等于sum
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return bool布尔型
*/
bool hasPathSum(TreeNode* root, int sum) {
// write code here
if(root==NULL)//空树直接返回false
return false;
int res=0;
res+=root->val;
if(root->right==NULL&&root->left==NULL&&res==sum)
return true;
bool leftData=hasPathSum(root->left, sum-res);
bool rightData=hasPathSum(root->right, sum-res);
if(leftData==true||rightData==true)
return true;
else return false;
}
};