LeetCode | 0226. Invert Binary Tree翻轉二叉樹【Python】

LeetCode 0226. Invert Binary Tree翻轉二叉樹【Easy】【Python】【二叉樹】【遞歸】

Problem

LeetCode

Invert a binary tree.

Example:

Input:

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

Output:

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

Trivia:
This problem was inspired by this original tweet by Max Howell:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.

問題

力扣

翻轉一棵二叉樹。

示例:

輸入:

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

輸出:

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

備註:
這個問題是受到 Max Howell 原問題 啓發的 :

谷歌:我們90%的工程師使用您編寫的軟件(Homebrew),但是您卻無法在面試時在白板上寫出翻轉二叉樹這道題,這太糟糕了。

思路

解法一

遞歸

前序遍歷二叉樹,如果當前節點有子樹,就交換左右子樹。
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 invertTree(self, root: TreeNode) -> TreeNode:
        # solution one: 遞歸
        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.invertTree(root.left)
        if root.right:
            self.invertTree(root.right)
        return root
解法二

用棧模擬二叉樹。
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 invertTree(self, root: TreeNode) -> TreeNode:
        # solution two: 棧
        if not root:
            return None
        # 葉子節點,直接返回自己
        if not root.left and not root.right:
            return root
        
        # 棧模擬二叉樹
        stack = [root]
        while stack:
            node = stack.pop()
            if node:
                node.left, node.right = node.right, node.left
                stack.append(node.right)
                stack.append(node.left)
        return root

代碼地址

GitHub鏈接

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