剑指Offer27-二叉树的镜像
每日几道leetcode刷刷题!
JZ-Offer27
题目描述
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
注意!这里要求的是返回它的镜像,返回的是二叉树(即返回根节点),而不是数组,
与 lc102 二叉树的层次遍历 类似(当注意这两者的区别所在),采用 BFS 算法会更容易理解,同时,由于镜像,所以需要交换左节点有右节点,即a.left, a.right = a.right, a.left
代码(BFS)
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if not root:
return
queue = [root] #存储当前层的节点
while queue:
n = len(queue)
for i in range(n):
a = queue.pop(0)
if a.left:
queue.append(a.left)
if a.right:
queue.append(a.right)
#注意此时,root.left 还是 root.left, root.right同理
a.left, a.right = a.right, a.left #交换左、右孩子
return root
递归
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if not root:
return root
else:
root.right, root.left = root.left, root.right # 交换左右节点
self.mirrorTree(root.right) # 对右节点递归
self.mirrorTree(root.left) # 对左节点递归
return root