-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathpath-sum.cpp
More file actions
46 lines (36 loc) · 1.01 KB
/
path-sum.cpp
File metadata and controls
46 lines (36 loc) · 1.01 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
// this one is tricky, should practice again
#include "leetcode.h"
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if (root == NULL) return false;
return hasPathSum_recursive(root, sum);
}
bool hasPathSum_recursive(TreeNode *root, int sum) {
// if (root == NULL) {
// return sum == 0;
// }
if (root->left == NULL && root->right == NULL) {
// it's a leaf node
return sum == root->val;
}
bool result = false;
if (root->left != NULL) {
result = hasPathSum_recursive(root->left, sum - root->val);
if (result) return true;
}
if (root->right != NULL) {
result = hasPathSum_recursive(root->right, sum - root->val);
}
return result;
}
};
int main(int argc, char const *argv[])
{
string tree("5 4 11 7 # # 2 # # # 8 13 # # 4 # 1 # #");
TreeNode* root = deserialize_tree(tree);
preorder_cout(root);
Solution sol;
cout << sol.hasPathSum(NULL, 0) << endl;
return 0;
}