版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
有点变化的经典广度优先
/*
// 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) {
vector<vector<int>>ans;
vector<int>tmp;
queue<Node *>q;
if(!root) return ans;
q.push(root);
while(!q.empty())
{
queue<Node *>q1;
tmp.clear();
while(!q.empty())
{
tmp.push_back(q.front()->val);
q1.push(q.front());
q.pop();
}
ans.push_back(tmp);
while(!q1.empty())
{
Node * t = q1.front();
for(int i = 0;i<(t->children).size();i++)
{
if(t->children[i])
q.push(t->children[i]);
}
q1.pop();
}
}
return ans;
}
};