-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem129.cpp
43 lines (40 loc) · 1.2 KB
/
problem129.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
class Solution {
public:
int res;
string str;
// solution 1:
int sumNumbers(TreeNode* root) {
res = 0;
str = "";
fun(root);
return res;
}
void fun(TreeNode* root){
if(root == nullptr)
return ;
if(root->left == nullptr && root->right == nullptr)
{
str += to_string(root->val), res += stoi(str), str.pop_back();
return;
}
// call left
// peek
str+= to_string(root->val);fun(root->left);
// leave
str.pop_back();
// call right
// peek
str+= to_string(root->val);fun(root->right);
// leave
str.pop_back();
}
// solution 2
// int sumNumbers(TreeNode* root, int res = 0) {
// if(!root)
// return 0;
// res = res*10 + root->val;
// if(!root->left && !root->right)
// return res;
// return sumNumbers(root->left, res) + sumNumbers(root->right, res);
// }
};