牛客網《劍指offer》之Python2.7實現:二叉樹的映象
阿新 • • 發佈:2018-12-14
題目描述
操作給定的二叉樹,將其變換為源二叉樹的映象。
輸入描述:
二叉樹的映象定義:源二叉樹
思路
遞迴遍歷二叉樹,交換左右子樹即可,需要注意葉節點的處理
程式碼
# -*- 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 is None: return temp = root.left root.left = root.right root.right = temp self.Mirror(root.left) self.Mirror(root.right) return root