题目
思路
递归 或者 栈。 递归就是左右子树的解构成了二叉树的解。栈就是由根节点开始,遍历各节点,执行交换操作。
注意, 因为root.left=mirror(root.right)已经把root.left改变了,所以如果是分步实现左右子树的镜像交换,则需要在被改之前先把root.left存起来,后面调用。
### 简化版
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if not root:
return None #### 终止条件
root.left, root.right = self.mirrorTree(root.right), self.mirrorTree(root.left)
return root
### 辅助变量版
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if not root:
return None #### 终止条件
tmp = root.left
root.left = self.mirrorTree(root.right)
root.right = self.mirrorTree(tmp)
return root
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if not root: return
stack = [root]
while stack:
node = stack.pop()
if node: ### 终止条件
stack.append(node.left)
stack.append(node.right)
node.left, node.right = node.right, node.left
return root
######## 实测 先交换再append 效率更高:
class Solution:
def invertTree(self, root):
stack = [root]
while stack:
node = stack.pop()
if node:
node.left, node.right = node.right, node.left
stack.append(node.right)
stack.append(node.left)
return root
来源:力扣(LeetCode)
参考链接:戳