From 7aad63754097b29ce05a36d8a8c1cfa7b711fb40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=97=A4=E9=9C=B2?= <080301087@163.com> Date: Tue, 8 Jun 2021 10:06:37 +0800 Subject: [PATCH] =?UTF-8?q?Update=200102.=E4=BA=8C=E5=8F=89=E6=A0=91?= =?UTF-8?q?=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index c7fdf776..ca24cc8f 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -98,15 +98,13 @@ class Solution: out_list = [] while quene: + length = len(queue) # 这里一定要先求出队列的长度,不能用range(len(queue)),因为queue长度是变化的 in_list = [] - for _ in range(len(quene)): - node = quene.pop(0) - in_list.append(node.val) - if node.left: - quene.append(node.left) - if node.right: - quene.append(node.right) - + 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