41 lines
894 B
Java
41 lines
894 B
Java
/*
|
|
// 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 {
|
|
private void levelOrder(ArrayList<List<Integer>> traversal, Node root, int level) {
|
|
if (root == null) {
|
|
return;
|
|
}
|
|
|
|
if (level >= traversal.size()) {
|
|
traversal.add(new ArrayList<Integer>());
|
|
}
|
|
traversal.get(level).add(root.val);
|
|
|
|
for (var child : root.children) {
|
|
levelOrder(traversal, child, level + 1);
|
|
}
|
|
}
|
|
|
|
public List<List<Integer>> levelOrder(Node root) {
|
|
ArrayList<List<Integer>> result = new ArrayList<>();
|
|
levelOrder(result, root, 0);
|
|
return result;
|
|
}
|
|
}
|