-
Notifications
You must be signed in to change notification settings - Fork 1
/
112.cpp
41 lines (32 loc) · 956 Bytes
/
112.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
40
41
// 112. Path Sum - https://leetcode.com/problems/path-sum
#include "bits/stdc++.h"
using namespace std;
// 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) {
return pre_order(root, 0, sum);
}
bool pre_order(TreeNode* node, int cur_sum, int target_sum) {
if (node == nullptr) { return false; }
cur_sum += node->val;
if (is_leaf(node) && cur_sum == target_sum) {
return true;
}
return pre_order(node->left, cur_sum, target_sum) ||
pre_order(node->right, cur_sum, target_sum);
}
bool is_leaf(TreeNode* node) {
return node->left == nullptr && node->right == nullptr;
}
};
int main() {
ios::sync_with_stdio(false);
return 0;
}