题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
解答
# coding:utf-8
class ListNode:
def __init__(self,x, left=None, right=None):
self.val = x
self.left = left
self.right = right
class Solution:
# 返回镜像树的根节点
def Mirror(self, root):
# write code here
nodeList = [root]
while nodeList:
curNode = nodeList.pop(0)
if not curNode:
return None
if curNode.left:
nodeList.append(curNode.left)
if curNode.right:
nodeList.append(curNode.right)
curNode.left, curNode.right = curNode.right, curNode.left
return root
a = ListNode('a')
b = ListNode('b')
c = ListNode('c')
d = ListNode('d')
f = ListNode('a')
e = ListNode('e')
f.left = b
f.right = e
b.left = c
c.left = d
e.right = a
ret = Solution().Mirror(f)
print ret.left.val
print ret.right.val
结束!