这叫对称二叉树:
- #一个递归 考虑从上至下递归,判断每对节点是否对称
#比较完整的写出递归函数的顺序
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root: return True#特例
return self.recur(root.left,root.right)
def recur(self, roota: TreeNode,rootb: TreeNode):
if not roota and not rootb:#跳出递归的条件
return True
if not roota or not rootb or roota.val!=rootb.val:#何时返回false
return False
else:#递归
return self.recur(roota.right,rootb.left) and self.recur(roota.left,rootb.right)
- #接着上一题(offer27)的笨蛋做法
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root: return True#特例
return str(root)==str(self.mirror(root))#不转换为str就会有不顾null位置的情况
def mirror(self, root: TreeNode):
if not root:return
root.left,root.right=self.mirror(root.right),self.mirror(root.left)
return root