forked from kishanrajput23/leetcode-solutions-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path112. PathSum.cpp
More file actions
31 lines (26 loc) · 741 Bytes
/
112. PathSum.cpp
File metadata and controls
31 lines (26 loc) · 741 Bytes
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
// https://leetcode.com/problems/path-sum
// 98% efficient solution
class Solution {
public:
int pathSum = 0;
bool pathFound = false;
bool hasPathSum(TreeNode* root, int targetSum)
{
if(root != NULL)
{
pathSum += root->val;
if(root->left == NULL && root->right == NULL)
{
if(pathSum == targetSum)
pathFound = true;
}
else
{
hasPathSum(root->left, targetSum);
hasPathSum(root->right, targetSum);
}
pathSum -= root->val;
}
return (pathFound == true) ? true : false;
}
};