-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSum_root_to_leaf_numbers.cpp
64 lines (58 loc) · 1.19 KB
/
Sum_root_to_leaf_numbers.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x):val(x),left(NULL),right(NULL){}
};
void sum_cur(vector<vector<int> >& re,vector<int>& cur,TreeNode* t)
{
cur.push_back(t->val);
if (t->left == NULL && t->right == NULL)
{
re.push_back(cur);
return;
}
if (t->left != NULL)
{
sum_cur(re,cur,t->left);
cur.pop_back();
}
if (t->right != NULL)
{
sum_cur(re,cur,t->right);
cur.pop_back();
}
return;
}
int sumNumbers(TreeNode* root)
{
vector<vector<int> > re;
vector<int> cur;
if (root == NULL)
return 0;
sum_cur(re,cur,root);
int sum = 0;
for (int i = 0; i < re.size(); i++)
{
int tmpsum = re[i][0];
for (int j = 1; j < re[i].size(); j++)
{tmpsum = tmpsum * 10 + re[i][j];}
sum += tmpsum;
}
return sum;
}
int main()
{
TreeNode* t = new TreeNode(4);
t->left = new TreeNode(9);
t->right = new TreeNode(0);
t->right->left = new TreeNode(2);
t->left->right = new TreeNode(1);
int sum = sumNumbers(t);
cout<<sum;
return 0;
}