Skip to content

Commit ae62dfb

Browse files
committed
1
1 parent 55207be commit ae62dfb

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

PathSum/PathSum.cpp

+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/**
2+
* Definition for binary tree
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
bool hasPathSum(TreeNode *root, int sum) {
13+
// Start typing your C/C++ solution below
14+
// DO NOT write int main() function
15+
if (root == NULL)
16+
return false;
17+
return dfs(root, 0, sum);
18+
19+
}
20+
21+
bool dfs(TreeNode *node, int value, int target) {
22+
if (node->left == NULL && node->right == NULL) {
23+
if (value + node->val == target)
24+
return true;
25+
else
26+
return false;
27+
}
28+
bool flag = false;
29+
if (node->left)
30+
flag = dfs(node->left, node->val + value, target);
31+
if (flag) return true;
32+
if (node->right)
33+
return dfs(node->right, node->val + value, target);
34+
}
35+
};

0 commit comments

Comments
 (0)