面試27題:
題目:二叉樹的鏡像
題:操作給定的二叉樹,將其變換為源二叉樹的鏡像。
輸入描述:
二叉樹的鏡像定義:源二叉樹 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 not root: return if not root.left and not root.right: return pTemp=root.left root.left=root.right root.right=pTemp if root.left: self.Mirror(root.left) if root.right: self.Mirror(root.right)