本题同样是二叉树的层序遍历的扩展,只不过二叉树每个节点的子节点只有左右节点,而N叉树的子节点是一个数组,层序遍历到一个节点时,需要将这个节点的子节点数组的每个节点都入队。
代码如下:
/*
// Definition for a Node.
class Node {
public:int val;vector<Node*> children;Node() {}Node(int _val) {val = _val;}Node(int _val, vector<Node*> _children) {val = _val;children = _children;}
};
*/class Solution {
public:vector<vector<int>> levelOrder(Node* root) {vector<vector<int>> result;queue<Node*> que;if(root != nullptr){que.push(root);}while(!que.empty()){int size = que.size();vector<int> vec;for(int i = 0; i < size; i++){Node * cur = que.front();que.pop();vec.push_back(cur->val);for(int j = 0; j < cur->children.size(); j++){if(cur->children[j] != nullptr) {que.push(cur->children[j]);}}}result.push_back(vec);}return result;}
};