題目描述
操作給定的二叉樹,將其變換爲源二叉樹的鏡像。
二叉樹的鏡像定義:
源二叉樹 鏡像二叉樹
8 8
/ \ / \
6 10 10 6
/ \ / \ / \ / \
5 7 9 11 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
思路:
二叉樹的常見操作就是遞歸,不妨從遞歸的思路來思考此題
# -*- 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 root
node = root.left # node中間鍵 指向根節點left
root.left = root.right # 左子節點 = 右字節點
root.right = node # 右子節點指向左子節點
self.Mirror(root.left) # 遞歸左子節點,循環執行 節點交換操作
self.Mirror(root.right) # # 遞歸右子節點,循環執行 節點交換操作
return root # 返回主節點root