https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof/
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
思路:判断一棵二叉树是否对称,即判断其左子树的左子树与右子树的右子树,左子树的右子树与右子树的左子树是否相同。
# 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 isSym(self, left, right):
if left is None and right is None:
return True
if left is None or right is None:
return False
if left.val != right.val:
return False
return self.isSym(left.left, right.right) and self.isSym(left.right, right.left)
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
if root.left is None and root.right is None:
return True
if root.left is None or root.right is None:
return False
return self.isSym(root.left, root.right)