-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4_sumNum.cpp
49 lines (47 loc) · 1.16 KB
/
4_sumNum.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
46
47
48
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
void sumNumReCur(TreeNode* root, int* curSum, int parent){
if(root == NULL){
return;
}
int curValue = parent*10 + root->val;
if(root->left == NULL && root->right == NULL){
curSum += curValue;
return;
}
if(root->left != NULL)
sumNumReCur(root->left, curSum, curValue);
if(root->right != NULL)
sumNumReCur(root->right, curSum, curValue);
}
int sumNumbers(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == NULL){ return 0;}
int sum = 0;
sumNumReCur(root, &sum, 0);
return sum;
}
};
int main(){
Solution s;
int sum = s.sumNumbers(new TreeNode(9));
cout<<sum<<endl;
}