-
Notifications
You must be signed in to change notification settings - Fork 0
/
7.Sum root to leaf numbers
40 lines (37 loc) · 1011 Bytes
/
7.Sum root to leaf numbers
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
class Solution {
public:
void helper(TreeNode* root , vector <int> &ans , vector < vector <int> >&res)
{
if(root == NULL)
{
return ;
}
if(root->right == NULL && root->left == NULL)
{
ans.push_back(root->val) ;
res.push_back(ans) ;
ans.pop_back() ;
}
ans.push_back(root->val) ;
helper(root->left , ans , res) ;
helper(root->right , ans , res ) ;
ans.pop_back() ;
}
int sumNumbers(TreeNode* root) {
vector < vector <int> > res ;
vector <int> ans ;
helper(root , ans , res) ;
int tsum = 0 ;
for(int i = 0 ; i < res.size() ; i++)
{
int s = 0 ;
for(int j = 0 ; j < res[i].size() ; j++)
{
s = s * 10 + res[i][j] ;
}
tsum = tsum + s ;
//cout << tsum ;
}
return tsum;
}
};