解题思路
同样是根据二叉树模板做出一些改变,在二叉树的层序遍历中,每一个节点的子节点数上限是2,因此无需通过循环检查子节点合法性。由于本题的节点为N叉树,需要遍历储存节点的children数组来检查子节点合法性。这里使用STL容器的迭代器进行循环遍历,即:
for(auto it = (top->children).begin(); it != (top->children).end(); it++)
{
if(*it != nullptr) //检查合法性
temp.push(*it);
}
完整代码
class Solution {
public:
vector<vector<int>> levelOrder(Node* root)
{
vector<vector<int>> ans;
queue<Node*> temp;
if(root != nullptr)
temp.push(root);
else
return ans;
while(!temp.empty())
{
vector<int> layer;
int num = temp.size();
for(int i = 0; i < num; i++)
{
Node* top = temp.front();
temp.pop();
layer.push_back(top->val);
for(auto it = (top->children).begin(); it != (top->children).end(); it++)
{
if(*it != nullptr) //注意检查合法性
temp.push(*it);
}
}
ans.push_back(layer);
}
return ans;
}
};