-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path112_has_path_sum.cc
50 lines (43 loc) · 1004 Bytes
/
112_has_path_sum.cc
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
50
#include <vector>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include <iostream>
#include <tuple>
#include <queue>
#include <stack>
using namespace::std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool dfs(TreeNode* root, int val, int sum) {
if (root == nullptr)
return false;
if (root->left == nullptr && root->right == nullptr) {
if (val + root->val == sum)
return true;
else
return false;
}
if (dfs(root->left, val + root->val, sum))
return true;
if (dfs(root->right, val + root->val, sum))
return true;
return false;
}
bool hasPathSum(TreeNode* root, int sum) {
if (root == nullptr)
return false;
return dfs(root, 0, sum);
}
};
int main()
{
return 0;
}