-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem_0129_sumNumbers.cc
68 lines (63 loc) · 1.32 KB
/
Problem_0129_sumNumbers.cc
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
65
66
67
68
#include <iostream>
#include <queue>
#include <tuple>
#include <vector>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode() : val(0), left(nullptr), right(nullptr) {}
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
class Solution
{
public:
int dfs(TreeNode *cur, int sum)
{
if (cur == nullptr)
{
return 0;
}
sum = sum * 10 + cur->val;
if (cur->left == nullptr && cur->right == nullptr)
{
return sum;
}
return dfs(cur->left, sum) + dfs(cur->right, sum);
}
int sumNumbers(TreeNode *root) { return dfs(root, 0); }
int bfs(TreeNode *root)
{
if (root == nullptr)
{
return 0;
}
int sum = 0;
queue<tuple<TreeNode *, int>> q;
q.push({root, root->val});
while (!q.empty())
{
auto [node, num] = q.front();
q.pop();
if (node->left == nullptr && node->right == nullptr)
{
sum += num;
}
else
{
if (node->left != nullptr)
{
q.push({node->left, num * 10 + node->left->val});
}
if (node->right != nullptr)
{
q.push({node->right, num * 10 + node->right->val});
}
}
}
return sum;
}
};