题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
思路:
对于任意一个根节点,其节点与所有子树节点构成了一个基本单元,设置一个镜像函数,将左结点和右结点调换,后面依次调用前面的函数,加以判断即可。
#coding:utf-8
class TreeNode:
def __init__(self,x):
self.val = x
self.left = None
self.right = None
class Solution:
def swap(self,root):
self.temp = root.left
root.left = root.right
root.right = self.temp
def Mirror(self,root):
if root == None:
return root
else:
self.swap(root)
self.Mirror(root.left)
self.Mirror(root.right)
return root
if __name__ == '__main__':
root = TreeNode(8)
node1 = TreeNode(6)
node2 = TreeNode(10)
node3 = TreeNode(5)
node4 = TreeNode(7)
node5 = TreeNode(9)
node6 = TreeNode(11)
root.left = node1
root.right = node2
root.left.left = node3
root.left.right = node4
root.right.left = node5
root.right.right = node6
s = Solution()
s.Mirror(root)