解法1是DFS,解法2是BFS
DFS应用了前序遍历的方法,BFS用的层序遍历求和,qt表示用队列存储树节点指针,qi表示存储到该节点的路径和
cpp
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if(!root){
return false;
}
bool flag=false;
bool& exist=flag;
// dfs(root,0,targetSum,exist);
bfs(root,targetSum,exist);
return exist;
}
void dfs(TreeNode* tn,int sum,int targetSum,bool& exist){
if(!tn){
return;
}
sum+=tn->val;
if(sum==targetSum&&!tn->left&&!tn->right){
exist=true;
return;
}
dfs(tn->left,sum,targetSum,exist);
dfs(tn->right,sum,targetSum,exist);
}
void bfs(TreeNode*node,int targetSum,bool& exist){
if(!node){
return;
}
if(!node->left&&!node->right){
exist=targetSum==node->val;
}
queue<TreeNode*> qt;
queue<int> qi;
qt.push(node);
qi.push(node->val);
while(!qt.empty()){
int sz=qt.size();
for(int i=0;i<sz;++i){
TreeNode* tn=qt.front();
int sum=qi.front();
if(tn->left){
int sum1=tn->left->val+sum;
if(!tn->left->left&&!tn->left->right&&sum1==targetSum){
exist=true;
return;
}
qt.push(tn->left);
qi.push(sum1);
}
if(tn->right){
int sum1=tn->right->val+sum;
if(!tn->right->left&&!tn->right->right&&sum1==targetSum){
exist=true;
return;
}
qt.push(tn->right);
qi.push(sum1);
}
qt.pop();
qi.pop();
}
}
}
};