-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpath_sum.cpp
More file actions
33 lines (29 loc) · 773 Bytes
/
path_sum.cpp
File metadata and controls
33 lines (29 loc) · 773 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
29
30
31
32
33
// 112. Path Sum: https://leetcode.com/problems/path-sum/
// Author: xianfeng.zhu@gmail.com
#include <cassert>
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
bool hasPathSum(TreeNode* root, int sum) {
if (root == nullptr) {
return false;
} else if (root->left == nullptr && root->right == nullptr) {
return (sum == root->val);
}
sum -= root->val;
return (hasPathSum(root->left, sum) || hasPathSum(root->right, sum));
}
};
int main(int argc, char* argv[]) {
TreeNode* root = nullptr;
int sum = 0;
const bool ret = Solution().hasPathSum(root, sum);
assert(not ret);
return 0;
}