-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path112.cpp
More file actions
28 lines (28 loc) · 763 Bytes
/
112.cpp
File metadata and controls
28 lines (28 loc) · 763 Bytes
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
//Path sum
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
// 注意sum可以为负值,空树时永远返回false;深度优先搜索
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if(root == NULL)
return false;
if(root->val == sum)
if(root->left == NULL && root->right == NULL)
return true;
bool l = false;
if(root->left != NULL)
l = hasPathSum(root->left, sum - root->val);
if(l) return true;
if(root->right != NULL)
return hasPathSum(root->right, sum - root->val);
return false;
}
};