mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-10 00:09:06 +01:00
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;
|
|
}
|
|
}
|