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:
parent
0bb6581d69
commit
23a0bb299a
1 changed files with 41 additions and 0 deletions
41
problems/n-ary-tree-level-order-traversal.java
Normal file
41
problems/n-ary-tree-level-order-traversal.java
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue