题目
思路
递归,和判断两个树是否相同原理类似,反转映射。
代码
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def symmetric(self, p, q):
if not p and not q: return True
if not p and q or not q and p: return False
if p.val != q.val: return False
return self.symmetric(p.right, q.left) and self.symmetric(p.left, q.right)
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
return self.symmetric(root, root)