101. 对称二叉树 - 力扣(LeetCode)
一、递归解法:
解法1
# 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:def isMirror(t1, t2):if not t1 and not t2: return Trueif not t1 or not t2: return Falsereturn t1.val == t2.val and \isMirror(t1.left, t2.right) and \isMirror(t1.right, t2.left)return isMirror(root.left, root.right)
以下两句的顺序不能颠倒:
if not t1 and not t2: return True if not t1 or not t2: return False
知识点:python中的or
在 Python 中:
①
A or B
表示:如果 A 为真(truthy),就返回 A;否则返回 B。
它是 逻辑“或”:只要有一个为真,结果就为真。
②Python 中的 or
是返回值表达式,不是单纯布尔值。
a = 0 b = 123 print(a or b) # 👉 123,因为 a 为 False,返回 b
表达式 | 结果 | 解释 |
0 or 123 | 123 | 0 为假 → 返回 123 |
[] or [1] | [1] | 空列表为假 → 返回非空列表 |
'a' or 'b' | 'a' | 'a' 为真 → 返回 'a' |
None or 1 | 1 | None 为假 → 返回 1 |
③用途
name = user_input or "Default Name"
如果用户输入是空的,就使用默认值 "Default Name"
④and的优先级高于or
⑤区别:
C/C++ 的 ||
只是返回布尔值(true
/ false
)
Python 的 or
会返回第一个为真的值或最后一个为假值,既是逻辑运算符也是表达式运算符(逻辑判断里是“有真则真”,表达式里是“遇真返回真值”)
解法2:
class Solution:def isSymmetric(self, root: TreeNode) -> bool:if not root:return Truereturn self.compare(root.left, root.right)def compare(self, left, right):# 1.排除空节点的情况if left == None and right == None: return Trueelif left != None and right == None: return Falseelif left == None and right != None: return False# 2.排除数值不相同的情况elif left.val != right.val: return False# 3. 剩余左右节点均不为空,且数值相同的情况# 此时做递归,对下一层做判断outside = self.compare(left.left, right.right)inside = self.compare(left.right, right.left)return inside and outside
二、迭代法