Skip to content

Commit e63f3aa

Browse files
authored
Create 112. PathSum.cpp
1 parent 53bb7a1 commit e63f3aa

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

112. PathSum.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// https://leetcode.com/problems/path-sum
2+
// 98% efficient solution
3+
4+
class Solution {
5+
public:
6+
int pathSum = 0;
7+
bool pathFound = false;
8+
9+
bool hasPathSum(TreeNode* root, int targetSum)
10+
{
11+
if(root != NULL)
12+
{
13+
pathSum += root->val;
14+
15+
if(root->left == NULL && root->right == NULL)
16+
{
17+
if(pathSum == targetSum)
18+
pathFound = true;
19+
}
20+
else
21+
{
22+
hasPathSum(root->left, targetSum);
23+
hasPathSum(root->right, targetSum);
24+
}
25+
26+
pathSum -= root->val;
27+
}
28+
29+
return (pathFound == true) ? true : false;
30+
}
31+
};

0 commit comments

Comments
 (0)