题目描述
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
4
/ \
2 7
/ \ / \
1 3 6 9镜像输出:
4
/ \
7 2
/ \ / \
9 6 3 1示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
解题思路1: 递归深度优先遍历
新建一个树, 将root进行深度优先遍历的同时给新树进行赋值, 将左右子节点进行镜像, 最后返回新的树
示例代码1:
def mirrorTree(root: TreeNode) -> TreeNode:
def dfs(r, n):
if r or n:
n.left, n.right = r.right, r.left
dfs(r.left, n.left)
dfs(r.right, n.right)
new = root
dfs(root, new)
return new
码优化: 其实不用新建树, 直接在原来的树上就可以进行反转. 不过这样原树的结构就变了
def mirrorTree(root: TreeNode) -> TreeNode:
if not root:
return
root.left, root.right = self.mirrorTree(root.right), self.mirrorTree(root.left)
return root
解题思路2: 辅助栈法
通过栈, 我们对root 进行遍历, 将遍历到的每个节点的左右节点镜像
示例代码2:
def mirrorTree(root: TreeNode) -> TreeNode:
if not root:
return None
stack = [root]
while stack:
temp = stack.pop()
temp.left, temp.right = temp.right, temp.left
if temp.left:
stack.append(temp.left)
if temp.right:
stack.append(temp.right)
return root