【算法训练】剑指offer#27 二叉树的镜像
一、描述
剑指 Offer 27. 二叉树的镜像
请完成一个函数,输入一个二叉树,该函数输出它的镜像。

示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
二、思路
- 通过遍历调转所有节点的左右子树
def left_to_right(self, root):
node_l = TreeNode() # 空节点负责调转左右节点
node_r = TreeNode() # 空节点负责调转左右节点
if root:
# 如果节点不为空
if root.left:
# 如果左节点不为空
node_l = root.left
if root.right:
# 如果右节点不为空
node_r = root.right
root.right = node_l
root.left = node_r
self.left_to_right(root.left)
self.left_to_right(root.right)
if root并不能跳出递归,用if root and root.val试试
- 还是没有正确退出,但好歹结果是对的,但是会输出多余的0
输入:[4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1,0,0,0,0,0,0,0,0]
- 哦,找到原因了,遍历最后一层结点的时候将他们的空子节点也进行了对调,导致产生多余结果,需要多加一层判空
def left_to_right(self, root):
if root and root.val:
node_l = root.left
node_r = root.right
if root.left and root.right:
# 如果左右都有
root.right = node_l
root.left = node_r
self.left_to_right(root.left)
self.left_to_right(root.right)
elif root.left and not root.right:
# 左有右没有
root.right = node_l
root.left = None
self.left_to_right(root.left)
elif not root.left and root.right:
# 左没有右有
root.right = None
root.left = node_r
self.left_to_right(root.right)
判断还是有问题...
我好像个智障。。。
三、解题
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
self.left_to_right(root)
return root
def left_to_right(self, root):
if root and root.val:
node_l = root.left
node_r = root.right
root.right = node_l
root.left = node_r
if root.right:
self.left_to_right(root.right)
if root.left:
self.left_to_right(root.left)

浙公网安备 33010602011771号