27.二叉樹的鏡像

題目描述

操作給定的二叉樹,將其變換爲源二叉樹的鏡像。

輸入描述:

二叉樹的鏡像定義:源二叉樹 
    	    8
    	   /  \
    	  6   10
    	 / \  / \
    	5  7 9 11
    	鏡像二叉樹
    	    8
    	   /  \
    	  10   6
    	 / \  / \
    	11 9 7  5

思路:遞歸!就是不斷的對左子樹做鏡像,對右子樹做鏡像。交換完所有非葉節點的左右子節點後,就完成了。注意,不要盲目return None或者return root.....牛客的測試用例真的不全。

python題解:

# -*- 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
        tmp=root.left
        root.left=root.right
        root.right=tmp
        if root.left:  #如果左節點不爲空,將左節點的子樹轉換爲鏡像
            self.Mirror(root.left)
        if root.right: #如果右節點不爲空,將右節點的子樹轉換爲鏡像
            self.Mirror(root.right)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章