题目
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
思路
将问题转换为小的问题:如果一棵树是对称二叉树,则它的左子树和右子树相互对称。左子树的左子树等于右子树的右子树,左子树的右子树等于右子树的左子树,且根节点的val相等。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
return self.isMirror(root,root)
def isMirror(self, root1, root2) -> bool:
if not root1 and not root2: return True
if not root1 or not root2: return False
return self.isMirror(root1.left, root2.right) and self.isMirror(root1.right, root2.left) and root1.val == root2.val