題目描述
操作給定的二叉樹,將其變換為源二叉樹的鏡像,輸入描述:
二叉樹的鏡像定義:源二叉樹
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 root.left,root.right=root.right,root.left self.Mirror(root.left) self.Mirror(root.right) #關鍵是我不寫回傳root這個程式也能運行 return root
這個題目的意思是首先交換root下面的兩個節點,然后交換root下下層的兩個節點,最后回傳新的root的樹的根節點,
解法二:構造新的二叉樹,但是這個方法可以我們自行學習而不用在這個題目上,因為這個題目讓我們回傳的是原來的二叉樹而非新的二叉樹,不然測驗用例的通過情況為0,代碼如下:
# -*- 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 newTree = TreeNode(root.val)
#首先構造新的節點,然后將新的節點下面的兩個子樹分別進行替換,更改方向 newTree.right = self.Mirror(root.left) newTree.left = self.Mirror(root.right) return newTree
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/145120.html
標籤:其他
上一篇:844走迷宮
