From 83af7646e0e91bf195d22a15f453cbc37ab0bb59 Mon Sep 17 00:00:00 2001 From: ZerenZhang2022 <118794589+ZerenZhang2022@users.noreply.github.com> Date: Mon, 19 Dec 2022 15:32:28 -0500 Subject: [PATCH] =?UTF-8?q?Update=200226.=E7=BF=BB=E8=BD=AC=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit python层序遍历方法,和之前层序遍历一节的写法一致 --- problems/0226.翻转二叉树.md | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index ad2a7de2..e55e1240 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -359,7 +359,22 @@ class Solution: queue.append(node.right) return root ``` - +迭代法:广度优先遍历(层序遍历),和之前的层序遍历写法一致: +```python +class Solution: + def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: + if not root: return root + from collections import deque + que=deque([root]) + while que: + size=len(que) + for i in range(size): + cur=que.popleft() + cur.left, cur.right = cur.right, cur.left + if cur.left: que.append(cur.left) + if cur.right: que.append(cur.right) + return root +``` ### Go 递归版本的前序遍历