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