問題描述:
操作給定的二叉樹,將其變換爲源二叉樹的鏡像。
二叉樹的鏡像定義:源二叉樹
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 Mirror(self, root):
# write code here
if root == None:
return None
r = root
r.left, r.right = root.right, root.left
r.left = self.Mirror(r.left)
r.right = self.Mirror(r.right)
return r