# 429. N-ary Tree Level Order Traversal

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:

1. The depth of the tree is at most `1000`.
2. The total number of nodes is at most `5000`.

``````class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
if (!root) return {};
vector<vector<int>> res;
queue<Node*> q{{root}};
while (!q.empty()) {
vector<int> out;
for (int i = q.size(); i > 0; --i) {
auto t = q.front(); q.pop();
out.push_back(t->val);
if (!t->children.empty()) {
for (auto a : t->children) q.push(a);
}
}
res.push_back(out);
}
return res;
}
};
``````

``````class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
vector<vector<int>> res;
helper(root, 0, res);
return res;
}
void helper(Node* node, int level, vector<vector<int>>& res) {
if (!node) return;
if (res.size() <= level) res.resize(res.size() + 1);
res[level].push_back(node->val);
for (auto a : node->children) {
helper(a, level + 1, res);
}
}
};
``````

Binary Tree Level Order Traversal

N-ary Tree Preorder Traversal

N-ary Tree Postorder Traversal

https://leetcode.com/problems/n-ary-tree-level-order-traversal/description/

https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/156218/Typical-C++-recursive-solution

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation