题干:
代码:
// Definition for a Node.
class Node {
public:
int val;
vector<Node*> children;
Node(int _val, vector<Node*> _children) {
val = _val;
children = _children;
}
};
class Solution {
public:
vector<vector<int>> levelOrder(Node* root) {
queue<Node*>que;
vector<vector<int>>res;
if(root != NULL)que.push(root);
while(!que.empty()){
int size = que.size();
vector<int>tmp;
while(size--){
Node* node = que.front();
que.pop();
tmp.push_back(node -> val);
for(int i = 0; i < node -> children.size(); i++){//node->children.size()指当前节点的孩子数目
if(node -> children[i]) que.push(node -> children[i]);
}
}
res.push_back(tmp);
}
return res;
}
};
与层序遍历模板不同在于,将if(node->left(right))que.push(node->left(right))改为了:
for(int i = 0; i < node -> children.size(); i++){
if(node -> children[i]) que.push(node -> children[i]);
}
node->children.size()指的是当前节点的所有孩子节点个数
if(node -> children[i])指的是如果能扫到节点(即节点存在)就执行后面的步骤。