题目
题解
非递归
/**
* 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 hasPathSum(TreeNode* root, int sum) {
if(root == NULL)
return false;
vector<TreeNode*> vec;
vec.push_back(root);
while(!vec.empty()){
vector<TreeNode*> temp;
for(int i=0;i<vec.size();i++){
if(vec[i]->left == NULL && vec[i]->right == NULL){
if(vec[i]->val == sum)
return true;
}
if(vec[i]->left != NULL){
vec[i]->left->val += vec[i]->val;
temp.push_back(vec[i]->left);
}
if(vec[i]->right != NULL){
vec[i]->right->val += vec[i]->val;
temp.push_back(vec[i]->right);
}
}
vec = temp;
}
return false;
}
};
递归
/**
* 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 hasPathSum(TreeNode* root, int sum) {
if(root == NULL)
return false;
if(root->left == NULL && root->right == NULL){
if(root->val == sum)
return true;
}
return hasPathSum(root->left,sum-root->val) || hasPathSum(root->right,sum-root->val);
}
};