add: 220713

This commit is contained in:
Eat-Swap 2022-07-13 23:17:05 +08:00
parent af4c1e5a0c
commit f219ad7517
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
1 changed files with 37 additions and 0 deletions

37
cpp/2207/220713.cpp Normal file
View File

@ -0,0 +1,37 @@
#include <vector>
#include <queue>
#include <utility>
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
explicit TreeNode(int x, TreeNode* left = nullptr, TreeNode* right = nullptr) : val(x), left(left), right(right) {}
};
class Solution {
public:
std::vector<std::vector<int>> levelOrder(TreeNode* root) {
if (!root)
return {};
std::vector<std::vector<int>> ret {{}};
std::queue<std::pair<const TreeNode*, int>> q;
q.push({root, 0});
int cl = 0;
while (!q.empty()) {
const auto [v, l] = q.front();
q.pop();
if (l > cl) {
++cl;
ret.emplace_back();
}
ret.back().push_back(v->val);
if (v->left)
q.push({v->left, 1 + l});
if (v->right)
q.push({v->right, 1 + l});
}
return ret;
}
};