-
Notifications
You must be signed in to change notification settings - Fork 0
/
112.path-sum.cpp
49 lines (44 loc) · 1.11 KB
/
112.path-sum.cpp
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
39
40
41
42
43
44
45
46
47
48
49
/*
* @lc app=leetcode id=112 lang=cpp
*
* [112] Path Sum
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution
{
public:
bool hasPathSum_rec(TreeNode *root, int targetSum, int cur_sum)
{
// dfs
// basecase
if (!root)
{
return false;
}
// found leafe with target sum and no chlideren
if (root->val + cur_sum == targetSum && !root->left && !root->right)
{
return true;
}
else
{
return hasPathSum_rec(root->left, targetSum, cur_sum + root->val) || hasPathSum_rec(root->right, targetSum, cur_sum + root->val);
}
}
bool hasPathSum(TreeNode *root, int targetSum)
{
return hasPathSum_rec(root, targetSum, 0);
}
};
// @lc code=end