Given an n-ary tree, return the level order traversal of its nodes' values.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
Previous Questions
- Binary tree level order traversal
- Binary tree level order traversal - II
- Binary tree zig-zag level order traversal
- Average of levels
- Binary tree right side view
- largest value in each tree row
- Populating next right pointer
- The algorithm is same as the first question in the series, except that we traverse all the children of the root node, not just left and right.
class Solution {
private:
void levelOrderDFS(vector<vector<int>>& res, Node* root, int level)
{
if (root == NULL) return;
if (level == res.size()) res.push_back({});
res[level].push_back(root->val);
for (auto node : root->children) {
levelOrderDFS(res, node, level + 1);
}
}
public:
vector<vector<int>> levelOrder(Node* root)
{
vector<vector<int>> res;
levelOrderDFS(res, root, 0);
return res;
}
};
- The algorithm is same as the first question in the series, except that we push all the children of the root node in queue, not just left and right.
class Solution {
public:
vector<vector<int>> levelOrder(Node* root)
{
vector<vector<int>> res;
if (root == NULL)
return res;
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int sz = q.size();
vector<int> currlevel;
for (int i = 0; i < sz; i++) {
Node* temp = q.front(); q.pop();
for (auto n : temp->children)
q.push(n);
currlevel.push_back(temp->val);
}
res.push_back(currlevel);
}
return res;
}
};