题解 | #对称的二叉树#
对称的二叉树
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 isSym_lr(self,lroot: TreeNode, rroot: TreeNode) -> bool: # 传入左右两个子树,看是否对称 issym = False if lroot.val == rroot.val: # 想变成ture 前提val相等 if lroot.left and rroot.right and not(lroot.right or rroot.left): # 传入左树的左边和右树的右边 issym = self.isSym_lr(lroot.left, rroot.right) # 看子树是否对称 if lroot.right and rroot.left and not(lroot.left or rroot.right): # 看另一边 issym = self.isSym_lr(lroot.right, rroot.left) if lroot.left and rroot.right and lroot.right and rroot.left: issym = self.isSym_lr(lroot.right, rroot.left) and self.isSym_lr(lroot.left, rroot.right) if not (lroot.right or lroot.left or rroot.left or rroot.right): # 如果两边都没有子节点并且val相等,则True issym = True return issym def isSymmetrical(self,pRoot: TreeNode): if not pRoot or (not pRoot.left and not pRoot.right): return True if not pRoot.left or not pRoot.right: return False return self.isSym_lr(pRoot.left, pRoot.right)