lc.112 路径总和
![[Pasted image 20241128001603.png]]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
vector<int>vec;
sum(root,targetSum,vec,0);//第四个参数是当前这条路径的路径值
//检查vec中存储的路径值是否有等于目标值的
bool is=false;
for(int i=0;i<vec.size();i++){
if(vec[i]==targetSum){
is=true;
}
}
return is;
}
void sum(TreeNode* root, int targetSum,vector<int>&vec,int n)//引用传参
{
//如果是空结点
if(!root){return;}
//如果是叶子节点
if(!root->left&&!root->right){
vec.push_back(n+=root->val);//把当前这条路径的路径值压入vec保存
return;
}
//其他情况(有左右结点/只有一个左右节点)
sum(root->left,targetSum,vec,n+root->val);
sum(root->right,targetSum,vec,n+root->val);
}
};
This post is licensed under CC BY 4.0 by the author.