原题
思路:
bfs,每一层遍历一次加到一个vector,同时把该点的子元素加到queue中。
class Solution
{
public:
vector<vector<int>> levelOrder(Node *root)
{
vector<vector<int>> res;
if (root == NULL)
return res;
queue<Node *> q;
q.push(root);
while (!q.empty())
{
vector<int> v;
int len = q.size();
for (int i = 0; i < len; i++)
{
Node *temp = q.front();
q.pop();
v.push_back(temp->val);
for (auto &a : temp->children)
{
q.push(a);
}
}
res.push_back(v);
}
return res;
}
};