题解 | #对称的二叉树#
对称的二叉树
https://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb
# class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param pRoot TreeNode类 # @return bool布尔型 # 递归判断是否镜像 class Solution: def isSymmetrical(self , pRoot: TreeNode) -> bool: # write code here return self.tojudge(pRoot, pRoot) def tojudge(self, p , q): # p,q为待测的镜像两个节点 if not p and not q: return True # 都空,不用继续判断了,返回真 if p and not q: return False if q and not p: return False # 不对称则假 if p and q: if p.val != q.val: # 对称不相等也假 return False else: # 对称且相等则递归下去判断其子树对不对称 return self.tojudge(p.left, q.right) and self.tojudge(p.right, q.left)