File tree Expand file tree Collapse file tree 1 file changed +39
-1
lines changed Expand file tree Collapse file tree 1 file changed +39
-1
lines changed Original file line number Diff line number Diff line change @@ -562,6 +562,45 @@ public class N0107 {
562
562
}
563
563
```
564
564
565
+ ``` java
566
+ /**
567
+ * 思路和模板相同, 对收集答案的方式做了优化, 最后不需要反转
568
+ */
569
+ class Solution {
570
+ public List<List<Integer > > levelOrderBottom (TreeNode root ) {
571
+ // 利用链表可以进行 O(1) 头部插入, 这样最后答案不需要再反转
572
+ LinkedList<List<Integer > > ans = new LinkedList<> ();
573
+
574
+ Queue<TreeNode > q = new LinkedList<> ();
575
+
576
+ if (root != null ) q. offer(root);
577
+
578
+ while (! q. isEmpty()) {
579
+ int size = q. size();
580
+
581
+ List<Integer > temp = new ArrayList<> ();
582
+
583
+ for (int i = 0 ; i < size; i ++ ) {
584
+ TreeNode node = q. poll();
585
+
586
+ temp. add(node. val);
587
+
588
+ if (node. left != null ) q. offer(node. left);
589
+
590
+ if (node. right != null ) q. offer(node. right);
591
+ }
592
+
593
+ // 新遍历到的层插到头部, 这样就满足按照层次反序的要求
594
+ ans. addFirst(temp);
595
+ }
596
+
597
+ return ans;
598
+ }
599
+ }
600
+ ```
601
+
602
+
603
+
565
604
go:
566
605
567
606
``` GO
@@ -3013,4 +3052,3 @@ impl Solution {
3013
3052
<a href =" https://programmercarl.com/other/kstar.html" target =" _blank" >
3014
3053
<img src =" ../pics/网站星球宣传海报.jpg" width =" 1000" />
3015
3054
</a >
3016
-
You can’t perform that action at this time.
0 commit comments