題目:
Given the root of a binary tree, invert the tree, and return its root.
給定一棵二元樹,將其左右反轉後回傳
透過簡單的遞迴,這題不算太難
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root: #防止root即為None
return None
temp=root.right
root.right=root.left
root.left=temp
root.right=self.invertTree(root.right)
root.left=self.invertTree(root.left)
return root
將root的左右枝互換
接著再透過遞迴向下,將root的左右枝之左右枝互換
直到碰到None為止
工程全部結束後,我們便得到一棵反轉完的binary tree了
最後執行時間30ms(faster than 95.51%)
那我們下題見