1、题目描述
27二叉树的镜像https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/
226翻转二叉树https://leetcode-cn.com/problems/invert-binary-tree/
两题一模一样!
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
相似题:LeetCode101. 对称二叉树(递归和迭代) https://blog.youkuaiyun.com/IOT_victor/article/details/107117445
2、代码详解
力扣版的题解(动画理解)+辅助栈写法
递归法如下
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def mirrorTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root == None:
return None
tmp = root.left # 暂存 root 的左子节点
# 下两句顺序不能换,因为tmp的交换问题。当然也可以tmp = root.right,下两句便随之改变
# 递归 右子节点 mirrorTree(root.right) ,并将返回值作为 root 的 左子节点
root.left = self.mirrorTree(root.right)
# 递归 左子节点 mirrorTree(tmp) ,并将返回值作为 root 的 右子节点
root.right = self.mirrorTree(tmp)
return root
需要判断输入的结点为空或者输入的结点没有子树的情况。
# -*- coding:utf-8 -*-
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 递归实现
def Mirror(self, root):
if root == None:
return
if root.left == None and root.right == None:
return root
pTemp = root.left
root.left = root.right
root.right = pTemp
self.Mirror(root.left)
self.Mirror(root.right)
pNode1 = TreeNode(8)
pNode2 = TreeNode(6)
pNode3 = TreeNode(10)
pNode4 = TreeNode(5)
pNode5 = TreeNode(7)
pNode6 = TreeNode(9)
pNode7 = TreeNode(11)
pNode1.left = pNode2
pNode1.right = pNode3
pNode2.left = pNode4
pNode2.right = pNode5
pNode3.left = pNode6
pNode3.right = pNode7
S = Solution()
S.Mirror(pNode1)
print(pNode1.right.left.val)