LeetCode 429. N-ary Tree Level Order Traversal
原题链接
中等
作者:
JasonSun
,
2020-08-19 11:27:42
,
所有人可见
,
阅读 397
Tree Fold
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
const auto candidate = [&](std::unordered_map<int, std::vector<int>> self = {}) {
std::function<void(Node*, int)> fold = [&](Node* n, int level) {
if (n == nullptr) {
return;
}
else {
self[level].emplace_back(n->val);
for (const auto ch : n->children) {
fold(ch, level + 1);
}
}
};
return fold(root, 0), self;
}();
const auto solution = [&](std::vector<std::vector<int>> self = {}) {
self.resize(std::size(candidate));
for (const auto & [level, nodes] : candidate) {
std::copy(std::begin(nodes), std::end(nodes), std::back_inserter(self[level]));
}
return self;
}();
return solution;
}
};
BFS
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
struct state_t {
mutable std::deque<Node*> Q;
mutable int level_size;
};
const auto state = state_t {
.Q = root == nullptr ? std::deque<Node*>{} : std::deque<Node*>{root},
.level_size = root == nullptr ? 0 : 1
};
const auto solution = [&ST = state](std::vector<std::vector<int>> self = {}) {
while (not std::empty(ST.Q)) {
const auto cur_level_size = std::exchange(ST.level_size, 0);
self.emplace_back(std::vector<int>{});
for (int i = 0; i < cur_level_size; ++i) {
const auto curr_node = ST.Q.front();
ST.Q.pop_front();
self.back().emplace_back(curr_node->val);
for (const auto ch : curr_node->children) {
ST.Q.emplace_back(ch);
++ST.level_size;
}
}
}
return self;
}();
return solution;
}
};