题目
题解
- 递归+深度优先遍历
- 广度优先遍历
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
// class Solution {
// public:
// bool hasPathSum(TreeNode* root, int targetSum) {
// if(!root)
// return false;
// queue<TreeNode*> que;
// queue<int> quesum;
// que.push(root);
// quesum.push(root->val);
// while(!que.empty()){
// // int len=que.size();
// // for(int i=0;i<len;i++){
// auto node=que.front();
// que.pop();
// int tmp=quesum.front();
// quesum.pop();
// if(node->left==nullptr&&node->right==nullptr)
// if(tmp==targetSum)
// return true;
// if(node->left){
// que.push(node->left);
// quesum.push(node->left->val+tmp);
// }
// if(node->right){
// que.push(node->right);
// quesum.push(node->right->val+tmp);
// }
// // }
// }
// return false;
// }
// };
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if(!root)
return false;
if (root->left == nullptr && root->right == nullptr) {
return targetSum == root->val;
}
return hasPathSum(root->left, targetSum - root->val) ||
hasPathSum(root->right, targetSum - root->val);
}
};