劍指offer:二叉樹的映象
阿新 • • 發佈:2018-12-09
# -*- 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 self.Mirror(root.left) self.Mirror(root.right) tmp=root.left root.left=root.right root.right=tmp
二叉樹的映象定義:源二叉樹 8 / \ 6 10 / \ / \ 5 7 9 11 映象二叉樹 8 / \ 10 6 / \ / \ 11 9 7 5
映象二叉樹就是左右子節點是顛倒的,注意是整個子樹都去顛倒,而不是節點位置對換。遞迴做起來比較簡單,將左右子節點對換之後,在遞迴到左右子節點中去。