Skip to content

Commit a11c78a

Browse files
添加0107二叉树的层序遍历II 不需要反转答案的 Java 版本
1 parent ab7e2ff commit a11c78a

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

problems/0102.二叉树的层序遍历.md

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -562,6 +562,45 @@ public class N0107 {
562562
}
563563
```
564564

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+
565604
go:
566605

567606
```GO
@@ -3013,4 +3052,3 @@ impl Solution {
30133052
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
30143053
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
30153054
</a>
3016-

0 commit comments

Comments
 (0)