-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path129.cpp
More file actions
30 lines (29 loc) · 709 Bytes
/
Copy path129.cpp
File metadata and controls
30 lines (29 loc) · 709 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
// recursion-3ms.cpp
/**
* 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 {
void calc(TreeNode* root, int value, int& sum) {
if (root == nullptr)
return;
value = value * 10 + root->val;
if (root->left == nullptr && root->right == nullptr) {
sum += value;
return;
}
calc(root->left, value, sum);
calc(root->right, value, sum);
}
public:
int sumNumbers(TreeNode* root) {
int sum = 0;
calc(root, 0, sum);
return sum;
}
};