-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathsolution129.cpp
More file actions
64 lines (57 loc) · 1.08 KB
/
solution129.cpp
File metadata and controls
64 lines (57 loc) · 1.08 KB
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
/**
* Sum Root to Leaf Numbers
*
* cpselvis([email protected])
* September 7th, 2016
*/
#include<iostream>
#include<vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
int sumNumbers(TreeNode* root) {
vector<int> nums;
int ret = 0;
if (root == NULL)
{
return ret;
}
dfs(root, nums, 0);
for (auto i : nums)
{
ret += i;
}
return ret;
}
void dfs(TreeNode *root, vector<int> &nums, int num)
{
num = num * 10 + root -> val;
if (root -> left != NULL)
{
dfs(root -> left, nums, num);
}
if (root -> right != NULL)
{
dfs(root -> right, nums, num);
}
if (root -> left == NULL && root -> right == NULL)
{
nums.push_back(num);
}
}
};
int main(int argc, char **argv)
{
TreeNode *root;
// TreeNode *root = new TreeNode(1);
// root -> left = new TreeNode(0);
// root -> right = new TreeNode(3);
Solution s;
cout << s.sumNumbers(root) << endl;
}