LeetCode刷题实战429:N 叉树的层序遍历
Given an n-ary tree, return the level order traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
示例
解题
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> tmp;
int n=q.size();
for(int i=0;i<n;i++)
{
Node* t=q.front();
q.pop();
tmp.push_back(t->val);
for(int j=0;j<t->children.size();j++)
{
q.push(t->children[j]);
}
}
res.push_back(tmp);
}
return res;
}
};
赞 (0)