day24-2022.11.20
题目信息来源
作者:Krahets
链接:https://leetcode.cn/leetbook/read/illustration-of-algorithm
来源:力扣(LeetCode)
剑指 Offer 27. 二叉树的镜像
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
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]
题解:递归法
简单题。其实一开始做这个题,我看错了,以为是复制一个二叉树,就,复制失败了。。。
总结:遍历的两种方式递归法和辅助栈法。这个是用递归的方法。其实就是遍历树的一种方式,还有一种方式是用栈。下面可以尝试一下。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if not root:return
tmp = root.left
root.left = root.right
root.right = tmp
self.mirrorTree(root.left)
self.mirrorTree(root.right)
return root
题解:辅助栈法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if not root:return
stack = [root]
while stack:
node = stack.pop()
if node:
node.left, node.right = node.right, node.left
stack.append(node.left)
stack.append(node.right)
return root
参考发现复杂度有点多,空间复杂度,根据题解在 while
循环部分优化一下,有点类似于剪枝。然后就成了官方题解的样子。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if not root:return
stack = [root]
while stack:
node = stack.pop()
node.left, node.right = node.right, node.left
if node.left:stack.append(node.left)
if node.right:stack.append(node.right)
return root