|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 | 3 | import com.fishercoder.common.classes.Node;
|
| 4 | + |
4 | 5 | import java.util.ArrayList;
|
5 | 6 | import java.util.LinkedList;
|
6 | 7 | import java.util.List;
|
7 | 8 | import java.util.Queue;
|
8 | 9 |
|
9 |
| -/** |
10 |
| - * 429. N-ary Tree Level Order Traversal |
11 |
| - * |
12 |
| - * Given an n-ary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). |
13 |
| - * |
14 |
| - * For example, given a 3-ary tree: |
15 |
| - * |
16 |
| - * 1 |
17 |
| - * / | \ |
18 |
| - * 3 2 4 |
19 |
| - * / \ |
20 |
| - * 5 6 |
21 |
| - * |
22 |
| - * We should return its level order traversal: |
23 |
| - * |
24 |
| - * [ |
25 |
| - * [1], |
26 |
| - * [3,2,4], |
27 |
| - * [5,6] |
28 |
| - * ] |
29 |
| - * |
30 |
| - * |
31 |
| - * Note: |
32 |
| - * |
33 |
| - * The depth of the tree is at most 1000. |
34 |
| - * The total number of nodes is at most 5000. |
35 |
| - */ |
36 | 10 | public class _429 {
|
37 |
| - public static class Solution1 { |
38 |
| - public List<List<Integer>> levelOrder(Node root) { |
39 |
| - List<List<Integer>> result = new ArrayList<>(); |
40 |
| - if (root == null) { |
41 |
| - return result; |
42 |
| - } |
43 |
| - Queue<Node> queue = new LinkedList<>(); |
44 |
| - queue.offer(root); |
45 |
| - while (!queue.isEmpty()) { |
46 |
| - int size = queue.size(); |
47 |
| - List<Integer> level = new ArrayList<>(); |
48 |
| - for (int i = 0; i < size; i++) { |
49 |
| - Node currentNode = queue.poll(); |
50 |
| - if (currentNode != null) { |
51 |
| - level.add(currentNode.val); |
52 |
| - for (Node child : currentNode.children) { |
53 |
| - queue.offer(child); |
| 11 | + public static class Solution1 { |
| 12 | + public List<List<Integer>> levelOrder(Node root) { |
| 13 | + List<List<Integer>> result = new ArrayList<>(); |
| 14 | + if (root == null) { |
| 15 | + return result; |
| 16 | + } |
| 17 | + Queue<Node> queue = new LinkedList<>(); |
| 18 | + queue.offer(root); |
| 19 | + while (!queue.isEmpty()) { |
| 20 | + int size = queue.size(); |
| 21 | + List<Integer> level = new ArrayList<>(); |
| 22 | + for (int i = 0; i < size; i++) { |
| 23 | + Node currentNode = queue.poll(); |
| 24 | + if (currentNode != null) { |
| 25 | + level.add(currentNode.val); |
| 26 | + for (Node child : currentNode.children) { |
| 27 | + queue.offer(child); |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + result.add(level); |
54 | 32 | }
|
55 |
| - } |
| 33 | + return result; |
56 | 34 | }
|
57 |
| - result.add(level); |
58 |
| - } |
59 |
| - return result; |
60 | 35 | }
|
61 |
| - } |
62 | 36 | }
|
0 commit comments