LeetCode | 面試題27. 二叉樹的鏡像【劍指Offer】【Python】

LeetCode 面試題27. 二叉樹的鏡像【劍指Offer】【Easy】【Python】【二叉樹】【遞歸】

問題

力扣

請完成一個函數,輸入一個二叉樹,該函數輸出它的鏡像。

例如輸入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

鏡像輸出:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

示例 1:

輸入:root = [4,2,7,1,3,6,9]
輸出:[4,7,2,9,6,3,1]

限制:

0 <= 節點個數 <= 1000

注意:本題與主站 226 題 相同

思路

遞歸

前序遍歷二叉樹,如果當前節點有子樹,就交換左右子樹。
Python3代碼
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def mirrorTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return None
        # 葉子節點,直接返回自己
        if not root.left and not root.right:
            return root
        
        # 交換非葉子節點的左右兩棵子樹
        root.left, root.right = root.right, root.left
        if root.left:
            self.mirrorTree(root.left)
        if root.right:
            self.mirrorTree(root.right)
        return root

代碼地址

GitHub鏈接

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