From 775accb7fdb783c2ec253c59c4e387c852a22166 Mon Sep 17 00:00:00 2001 From: Lane Zhang Date: Thu, 24 Oct 2024 10:41:30 +0800 Subject: [PATCH] =?UTF-8?q?0226.=E7=BF=BB=E8=BD=AC=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91.md=20=E4=BF=AE=E6=AD=A3=E5=87=A0=E5=A4=84=20Python=20?= =?UTF-8?q?=E4=BB=A3=E7=A0=81=E4=B8=8D=E4=B8=A5=E8=B0=A8=E8=AF=B4=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0226.翻转二叉树.md | 40 ++++++++++++++------------------ 1 file changed, 17 insertions(+), 23 deletions(-) diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index e501b298..285f971a 100644 --- a/problems/0226.翻转二叉树.md +++ b/problems/0226.翻转二叉树.md @@ -81,7 +81,7 @@ if (root == NULL) return root; 3. 确定单层递归的逻辑 -因为是先前序遍历,所以先进行交换左右孩子节点,然后反转左子树,反转右子树。 +因为是前序遍历,所以先进行交换左右孩子节点,然后反转左子树,反转右子树。 ```cpp swap(root->left, root->right); @@ -348,14 +348,13 @@ class Solution: while stack: node = stack.pop() node.left, node.right = node.right, node.left + if node.right: + stack.append(node.right) if node.left: stack.append(node.left) - if node.right: - stack.append(node.right) return root ``` - 递归法:中序遍历: ```python # Definition for a binary tree node. @@ -374,7 +373,7 @@ class Solution: return root ``` -迭代法:中序遍历: +迭代法,伪中序遍历(结果是对的,看起来像是中序遍历,实际上它是前序遍历,只不过把中间节点处理逻辑放到了中间。还是要用'统一写法'才是真正的中序遍历): ```python # Definition for a binary tree node. # class TreeNode: @@ -386,18 +385,17 @@ class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root: return None - stack = [root] + stack = [root] while stack: - node = stack.pop() - if node.left: - stack.append(node.left) - node.left, node.right = node.right, node.left - if node.left: - stack.append(node.left) + node = stack.pop() + if node.right: + stack.append(node.right) + node.left, node.right = node.right, node.left # 放到中间,依然是前序遍历 + if node.right: + stack.append(node.right) return root ``` - 递归法:后序遍历: ```python # Definition for a binary tree node. @@ -416,7 +414,7 @@ class Solution: return root ``` -迭代法:后序遍历: +迭代法,伪后序遍历(结果是对的,看起来像是后序遍历,实际上它是前序遍历,只不过把中间节点处理逻辑放到了最后。还是要用'统一写法'才是真正的后序遍历): ```python # Definition for a binary tree node. # class TreeNode: @@ -427,23 +425,19 @@ class Solution: class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root: - return None - stack = [root] + return None + stack = [root] while stack: - node = stack.pop() + node = stack.pop() + if node.right: + stack.append(node.right) if node.left: stack.append(node.left) - if node.right: - stack.append(node.right) node.left, node.right = node.right, node.left return root ``` - - - - 迭代法:广度优先遍历(层序遍历): ```python # Definition for a binary tree node.