AcWing 39. 对称的二叉树python3
原题链接
简单
作者:
蜀小柒
,
2020-07-07 15:38:01
,
所有人可见
,
阅读 732
python 代码
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:#为空对称
return True
if root.left and not root.right or root.right and not root.left:#根节点左右存在一个不在就不对称
return False
if not root.left and root.right:#只有根节点对称
return True
tree=root.left
subtree=self.turn(root.right)
if self.isMatch(tree,subtree):#左子树和右子树镜面匹配则对称
return True
return False
def turn(self,subtree):#右子树的镜面
if not subtree:
return None
subtree.left,subtree.right=subtree.right,subtree.left
self.turn(subtree.left)
self.turn(subtree.right)
return subtree
def isMatch(self,A,B):#判断是否匹配
if not A and not B:
return True
if not A and B or not B and A:
return False
if A and B and A.val!=B.val:
return False
return self.isMatch(A.left,B.left) and self.isMatch(A.right,B.right)