# [LeetCode] N-ary Tree Level Order Traversal N叉树层序遍历

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 题目讲解汇总(持续更新中...)

posted @ 2018-09-18 23:59  Grandyang  阅读(3297)  评论(0编辑  收藏  举报