diff --git a/problems/0226.翻转二叉树.md b/problems/0226.翻转二叉树.md index 55dc3cbf..c34ca4bf 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.