题目链接
解析: 对多叉树进行层序遍历.子节点被放到了一个vector数组中,所以访问时只要遍历数组就可以了.
tip: 用队列辅助遍历,将每一层放入到queue中,然后将同一层的结点放到一个数组中实现层与层的区分.
solution:
/*
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node() {}
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
if(!root) return {};
vector<vector<int>> vec;
queue<Node*> q{{root}};
while(!q.empty())
{
vector<int> out;
for(int i = q.size()-1;i>=0;i--)
{
auto n = q.front();q.pop();
out.push_back(n->val);
if(!n->children.empty())
for(auto a:n->children) q.push(a);
}
vec.push_back(out);
}
return vec;
}
};