1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-09 15:59:06 +01:00

problems(java): add „429. N-ary Tree Level Order Traversal“

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2022-09-05 11:31:36 +02:00
parent 0bb6581d69
commit 23a0bb299a
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -0,0 +1,41 @@
/*
// 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;
}
}