題目:
Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
給定一個binary tree,檢定它是否對稱
這題其實有一點100.的感覺
只是變成兩個node右子節點要等於對方的左子節點,左子節點要等於對方的右子節點
# 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 isSymmetric(self, root: Optional[TreeNode]) -> bool:
tree1=root.left
tree2=root.right
def symornot(t1,t2):
if t1 is t2:
return True
elif t1 and t2 and t1.val==t2.val:
return symornot(t1.left,t2.right) and symornot(t1.right,t2.left)
else:
return False
return symornot(tree1,tree2)
一開始的root並不重要,我們只要檢查它的兩個子樹是否鏡面對稱即可
比的過程如果對稱且都不是None就遞迴繼續往下比
一None一非None回傳False(不對稱)
都為None回傳True(到底了)
完全檢查完就知道兩個子樹是否完全對稱了
最後執行時間35ms(faster than 91.94%)
那我們下題見