-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem_STOII_0049_sumNumbers.cc
54 lines (51 loc) · 1.11 KB
/
Problem_STOII_0049_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
#include <iostream>
#include <queue>
#include <tuple>
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) {}
};
// seem as leetcode 0129
// https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/
// Problem_0129_sumNumbers.cc
class Solution
{
public:
int sumNumbers(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;
}
};