Skip to content

Commit a1ff2ba

Browse files
committed
Time: 0 ms (100%), Space: 21.5 MB (28.01%) - LeetHub
1 parent 010672b commit a1ff2ba

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

0112-path-sum/0112-path-sum.cpp

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
class Solution {
13+
public:
14+
15+
bool bfs(TreeNode* root, int& targetSum, int sum){
16+
17+
sum+= root->val;
18+
19+
if(root->left==nullptr && root->right==nullptr){
20+
return (sum == targetSum);
21+
}
22+
23+
bool left = root->left != nullptr ? bfs(root->left,targetSum,sum) : false;
24+
bool right = root->right != nullptr ? bfs(root->right,targetSum,sum) : false;
25+
26+
return (left || right);
27+
28+
}
29+
30+
bool hasPathSum(TreeNode* root, int targetSum) {
31+
32+
if(root==nullptr) return false;
33+
34+
int sum=0;
35+
return bfs(root,targetSum,sum);
36+
}
37+
};

0 commit comments

Comments
 (0)