题目描述:
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.
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
vector<vector<int>> result;
if(root==NULL) return result;
queue<Node*> q;
q.push(root);
while(!q.empty())
{
int n=q.size();
vector<int> cur;
for(int i=0;i<n;i++)
{
Node* node=q.front();
q.pop();
cur.push_back(node->val);
for(Node* child:node->children)
q.push(child);
}
result.push_back(cur);
}
return result;
}
};
本文介绍了一种解决N叉树层次遍历问题的方法,通过使用队列实现从上到下,从左到右的层次遍历,返回每一层节点的值。此算法适用于深度最多为1000的树,总节点数不超过5000。
494

被折叠的 条评论
为什么被折叠?



