-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path112_Path Sum.cpp
More file actions
48 lines (40 loc) · 1.07 KB
/
112_Path Sum.cpp
File metadata and controls
48 lines (40 loc) · 1.07 KB
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
#include <iostream>
#include <queue>
#include <string>
#include <list>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (!root) return false;
bool flag = false;
dfs(root, 0, sum, flag);
return flag;
}
void dfs(TreeNode* p, int currsum, const int& sum, bool &flag){
if (!flag){
currsum += p->val;
if (!p->left && !p->right){ // go to the leaf nodes
if (currsum == sum) flag = true;
return;
}
if (p->left) dfs(p->left, currsum, sum, flag);
if (p->right) dfs(p->right, currsum, sum, flag);
}
}
};
int main() {
TreeNode *node1 = new TreeNode(1);
TreeNode *node2 = new TreeNode(2);
TreeNode *node3 = new TreeNode(3);
node2->left = node1; node2->right = node3;
Solution s;
cout << s.hasPathSum(node2, 4);
return 0;
}