解题思路:
非常常规的一道N叉树层次遍历问题,略微修改一下二叉树层次遍历的BFS模板就可以轻松解决,代码如下:
/*
// Definition for a Node.
class Node {
public:
int val;
vector children;
Node() {}
Node(int _val) {
val = _val;
}
Node(int _val, vector _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
vector<vector<int>> res;
if(root == nullptr) return res;
queue<Node*> q;
q.push(root);
while(!q.empty()) {
int n = q.size();
vector<int> temp;
for(int i = 0; i < n; i ++) {
Node* node = q.front();
q.pop();
temp.push_back(node->val);
for(auto& child : node->children) {
q.push(child);
}
}
res.push_back(move(temp));
}
return res;
}
};```
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)