|
9 | 9 |
|
10 | 10 | /**
|
11 | 11 | * 102. Binary Tree Level Order Traversal
|
12 |
| -
|
13 |
| -Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). |
14 |
| -
|
15 |
| -For example: |
16 |
| -Given binary tree [3,9,20,null,null,15,7], |
17 |
| -
|
18 |
| - 3 |
19 |
| - / \ |
20 |
| - 9 20 |
21 |
| - / \ |
22 |
| - 15 7 |
23 |
| -
|
24 |
| -return its level order traversal as: |
25 |
| -
|
26 |
| -[ |
27 |
| - [3], |
28 |
| - [9,20], |
29 |
| - [15,7] |
30 |
| -] |
31 |
| -*/ |
| 12 | + * |
| 13 | + * Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). |
| 14 | + * |
| 15 | + * For example: |
| 16 | + * Given binary tree [3,9,20,null,null,15,7], |
| 17 | + * 3 |
| 18 | + * / \ |
| 19 | + * 9 20 |
| 20 | + * / \ |
| 21 | + * 15 7 |
| 22 | + * |
| 23 | + * return its level order traversal as: |
| 24 | + * |
| 25 | + * [ |
| 26 | + * [3], |
| 27 | + * [9,20], |
| 28 | + * [15,7] |
| 29 | + * ] |
| 30 | + */ |
32 | 31 | public class _102 {
|
33 | 32 |
|
34 |
| - public static class Solution1 { |
35 |
| - public List<List<Integer>> levelOrder(TreeNode root) { |
36 |
| - List<List<Integer>> result = new ArrayList<>(); |
37 |
| - if (root == null) { |
38 |
| - return result; |
39 |
| - } |
40 |
| - Queue<TreeNode> queue = new LinkedList(); |
41 |
| - queue.offer(root); |
42 |
| - while (!queue.isEmpty()) { |
43 |
| - List<Integer> thisLevel = new ArrayList(); |
44 |
| - int size = queue.size(); |
45 |
| - for (int i = 0; i < size; i++) { |
46 |
| - TreeNode curr = queue.poll(); |
47 |
| - thisLevel.add(curr.val); |
48 |
| - if (curr.left != null) { |
49 |
| - queue.offer(curr.left); |
50 |
| - } |
51 |
| - if (curr.right != null) { |
52 |
| - queue.offer(curr.right); |
53 |
| - } |
| 33 | + public static class Solution1 { |
| 34 | + public List<List<Integer>> levelOrder(TreeNode root) { |
| 35 | + List<List<Integer>> result = new ArrayList<>(); |
| 36 | + if (root == null) { |
| 37 | + return result; |
| 38 | + } |
| 39 | + Queue<TreeNode> queue = new LinkedList(); |
| 40 | + queue.offer(root); |
| 41 | + while (!queue.isEmpty()) { |
| 42 | + List<Integer> thisLevel = new ArrayList(); |
| 43 | + int size = queue.size(); |
| 44 | + for (int i = 0; i < size; i++) { |
| 45 | + TreeNode curr = queue.poll(); |
| 46 | + thisLevel.add(curr.val); |
| 47 | + if (curr.left != null) { |
| 48 | + queue.offer(curr.left); |
| 49 | + } |
| 50 | + if (curr.right != null) { |
| 51 | + queue.offer(curr.right); |
| 52 | + } |
| 53 | + } |
| 54 | + result.add(thisLevel); |
| 55 | + } |
| 56 | + return result; |
54 | 57 | }
|
55 |
| - result.add(thisLevel); |
56 |
| - } |
57 |
| - return result; |
58 | 58 | }
|
59 |
| - } |
60 | 59 | }
|
0 commit comments