LeetCode 429. N 叉树的层序遍历
原题链接
中等
作者:
autumn_0
,
2024-09-28 10:05:12
,
所有人可见
,
阅读 4
/*
// 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) {
if(root == null) return List.of();
List<List<Integer>> ans = new ArrayList<>();
Queue<Node> q = new ArrayDeque<>();
q.add(root);
while(!q.isEmpty()){
int n = q.size();
List<Integer> vals = new ArrayList<>(n);
while(n -- > 0){
Node node = q.poll();
vals.add(node.val);
q.addAll(node.children);
}
ans.add(vals);
}
return ans;
}
}