Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example, given a 3-ary tree:
We should return its level order traversal:
[ [1], [3,2,4], [5,6] ]
Note:
The depth of the tree is at most 1000. The total number of nodes is at most 5000.
// 160ms, 24%
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
vector<vector<int>> res;
if (!root) return res;
vector<Node*> buf;
buf.push_back(root);
while (!buf.empty()) {
vector<Node*> tmpBuf;
tmpBuf.reserve(buf.size());
res.push_back({});
for (const auto& r : buf) {
res.back().push_back(r->val);
if (!r->children.empty())
tmpBuf.insert(tmpBuf.end(), r->children.begin(), r->children.end());
}
buf.swap(tmpBuf);
}
return res;
}
};