题目链接
层序遍历
/*
// Definition for a Node.
class Node {
public int val;
public List<Node> children;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
*/
class Solution {
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> list = new ArrayList();
LinkedList<Node> queue = new LinkedList<>();
if(root != null){
queue.offer(root);
}
while(!queue.isEmpty()){
List<Integer> list1 = new ArrayList();
int size = queue.size();
for(int i = 0; i < size; i++){
Node node = queue.poll();
// 与二叉树相比变化代码
list1.add(node.val);
if(node.children != null){
queue.addAll(node.children);
}
}
list.add(list1);
}
return list;
}
}