1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 01:49:41 +01:00
LeetCode/java/n-ary-tree-level-order-traversal.java
Matej Focko 2351dfd0ee
chore: unwrap one layer
Signed-off-by: Matej Focko <mfocko@redhat.com>
2023-12-12 14:36:00 +01:00

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;
}
}