From a11c78a19d95f7091681651e071f87fb169009e3 Mon Sep 17 00:00:00 2001 From: SUNLIFAN Date: Thu, 19 Jan 2023 09:58:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00107=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86II=20?= =?UTF-8?q?=E4=B8=8D=E9=9C=80=E8=A6=81=E5=8F=8D=E8=BD=AC=E7=AD=94=E6=A1=88?= =?UTF-8?q?=E7=9A=84=20Java=20=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...02\345\272\217\351\201\215\345\216\206.md" | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git "a/problems/0102.\344\272\214\345\217\211\346\240\221\347\232\204\345\261\202\345\272\217\351\201\215\345\216\206.md" "b/problems/0102.\344\272\214\345\217\211\346\240\221\347\232\204\345\261\202\345\272\217\351\201\215\345\216\206.md" index 220232a2b1..21f5147dd3 100644 --- "a/problems/0102.\344\272\214\345\217\211\346\240\221\347\232\204\345\261\202\345\272\217\351\201\215\345\216\206.md" +++ "b/problems/0102.\344\272\214\345\217\211\346\240\221\347\232\204\345\261\202\345\272\217\351\201\215\345\216\206.md" @@ -562,6 +562,45 @@ public class N0107 { } ``` +```java +/** + * 思路和模板相同, 对收集答案的方式做了优化, 最后不需要反转 + */ +class Solution { + public List> levelOrderBottom(TreeNode root) { + // 利用链表可以进行 O(1) 头部插入, 这样最后答案不需要再反转 + LinkedList> ans = new LinkedList<>(); + + Queue q = new LinkedList<>(); + + if (root != null) q.offer(root); + + while (!q.isEmpty()) { + int size = q.size(); + + List 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 @@ -3013,4 +3052,3 @@ impl Solution { -