Skip to content

Commit

Permalink
Merge pull request youngyangyang04#1867 from SUNLIFAN/master
Browse files Browse the repository at this point in the history
添加0107二叉树的层序遍历II 不需要反转答案的 Java 版本
  • Loading branch information
youngyangyang04 authored Jan 25, 2023
2 parents 2ffbb82 + a11c78a commit d3b241e
Showing 1 changed file with 39 additions and 1 deletion.
40 changes: 39 additions & 1 deletion problems/0102.二叉树的层序遍历.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -3015,4 +3054,3 @@ impl Solution {
<a href="https://programmercarl.com/other/kstar.html" target="_blank">
<img src="../pics/网站星球宣传海报.jpg" width="1000"/>
</a>

0 comments on commit d3b241e

Please sign in to comment.