Merge pull request #1867 from SUNLIFAN/master

添加0107二叉树的层序遍历II 不需要反转答案的 Java 版本
This commit is contained in:
程序员Carl
2023-01-25 17:11:33 +08:00
committed by GitHub

View File

@ -564,6 +564,45 @@ public class N0107 {
}
```
```java
/**
* 思路和模板相同, 对收集答案的方式做了优化, 最后不需要反转
*/
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
// 利用链表可以进行 O(1) 头部插入, 这样最后答案不需要再反转
LinkedList<List<Integer>> ans = new LinkedList<>();
Queue<TreeNode> q = new LinkedList<>();
if (root != null) q.offer(root);
while (!q.isEmpty()) {
int size = q.size();
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < size; i ++) {
TreeNode node = q.poll();
temp.add(node.val);
if (node.left != null) q.offer(node.left);
if (node.right != null) q.offer(node.right);
}
// 新遍历到的层插到头部, 这样就满足按照层次反序的要求
ans.addFirst(temp);
}
return ans;
}
}
```
go:
```GO
@ -3015,4 +3054,3 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>