From f5a5cd882f3725cc56a95541bb738025e7b05d89 Mon Sep 17 00:00:00 2001 From: Wen Liang Date: Thu, 2 Sep 2021 17:22:28 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=200102.=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=86.md=20Pyt?= =?UTF-8?q?hon3=E8=A7=A3=E6=B3=95=20=E4=BB=BB=E4=BD=95=E5=9C=A8=20list=20?= =?UTF-8?q?=E5=A4=B4=E9=83=A8=E8=BF=9B=E8=A1=8C=E7=9A=84=E6=93=8D=E4=BD=9C?= =?UTF-8?q?=E9=83=BD=E4=BC=9A=E6=8D=9F=E5=A4=B1=E4=B8=80=E5=AE=9A=E6=80=A7?= =?UTF-8?q?=E8=83=BD=20=E5=9C=A8=20Python=20=E4=B8=AD=E5=BA=94=E8=AF=A5?= =?UTF-8?q?=E4=BD=BF=E7=94=A8=20collections.deque=20=E4=BD=9C=E4=B8=BA?= =?UTF-8?q?=E9=98=9F=E5=88=97=E7=9A=84=E6=95=B0=E6=8D=AE=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=20=E5=9C=A8=E8=AF=A5=E6=95=B0=E6=8D=AE=E7=B1=BB=E5=9E=8B?= =?UTF-8?q?=E5=B7=A6=E5=8F=B3=E4=B8=A4=E7=AB=AF=E8=BF=BD=E5=8A=A0=E5=92=8C?= =?UTF-8?q?=E5=BC=B9=E5=87=BA=E5=85=83=E7=B4=A0=E7=9A=84=E6=97=B6=E9=97=B4?= =?UTF-8?q?=E5=A4=8D=E6=9D=82=E5=BA=A6=E9=83=BD=E6=8E=A5=E8=BF=91O(1)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 37 +++++++++++++---------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index a57a92aa..07708e5a 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -87,26 +87,31 @@ public: python代码: -```python +```python3 class Solution: + """二叉树层序遍历迭代解法""" + def levelOrder(self, root: TreeNode) -> List[List[int]]: + results = [] if not root: - return [] + return results + + from collections import deque + que = deque([root]) + + while que: + size = len(que) + result = [] + for _ in range(size): + cur = que.popleft() + result.append(cur.val) + if cur.left: + que.append(cur.left) + if cur.right: + que.append(cur.right) + results.append(result) - queue = [root] - out_list = [] - - while queue: - length = len(queue) - in_list = [] - for _ in range(length): - curnode = queue.pop(0) # (默认移除列表最后一个元素)这里需要移除队列最头上的那个 - in_list.append(curnode.val) - if curnode.left: queue.append(curnode.left) - if curnode.right: queue.append(curnode.right) - out_list.append(in_list) - - return out_list + return results ``` java: