-
Notifications
You must be signed in to change notification settings - Fork 0
/
112-PathSum.cpp
39 lines (36 loc) · 1.08 KB
/
112-PathSum.cpp
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
/*=============================================================================
# FileName: 112-PathSum.cpp
# Desc: AC, 12ms
# Author: Jian Huang
# Email: [email protected]
# HomePage: https://cn.linkedin.com/in/huangjian1993
# Version: 0.0.1
# LastChange: 2015-08-20 10:50:27
# History:
=============================================================================*/
#include <leetcode.h>
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;
}
if (!root->left && !root->right) {
return sum == root->val;
}
sum -= root->val;
if (root->left && hasPathSum(root->left, sum)) {
return true;
}
if (root->right && hasPathSum(root->right, sum)) {
return true;
}
return false;
}
};