简单题,一看就有思路那种,而且方法很多。
递归:
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root == NULL) return false;
if(root->left == NULL && root->right == NULL) return root->val == sum;
return hasPathSum(root->left, sum-root->val) || hasPathSum(root->right, sum-root->val);
}
};
遍历:
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root == NULL) return false;
queue<TreeNode *> q_node;
queue<int> q_val;
q_node.push(root);
q_val.push(root->val);
while(!q_node.empty()){
TreeNode *q_tmp = q_node.front();
int tmp = q_val.front();
q_node.pop();
q_val.pop();
if(q_tmp->left == NULL && q_tmp->right == NULL){
// 为叶子节点
if(tmp == sum) return true;
continue;
}
if(q_tmp->left != NULL){
q_node.push(q_tmp->left);
q_val.push(q_tmp->left->val + tmp);
}
if(q_tmp->right != NULL){
q_node.push(q_tmp->right);
q_val.push(q_tmp->right->val + tmp);
}
}
return false;
}
};