-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path129.cpp
45 lines (37 loc) · 974 Bytes
/
129.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
42
43
44
45
// 129. Sum Root to Leaf Numbers - https://leetcode.com/problems/sum-root-to-leaf-numbers
#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 {
private:
int total;
public:
int sumNumbers(TreeNode* root) {
total = 0;
pre_order(root, 0);
return total;
}
void pre_order(TreeNode* node, int cur_sum) {
if (node == nullptr) { return; }
cur_sum = 10 * cur_sum + node->val;
if (is_leaf(node)) {
total += cur_sum;
return;
}
pre_order(node->left, cur_sum);
pre_order(node->right, cur_sum);
}
bool is_leaf(TreeNode* node) {
return node->left == nullptr && node->right == nullptr;
}
};
int main() {
ios::sync_with_stdio(false);
return 0;
}