给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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
说明:
如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
迭代:
# 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):
"""
:type root: TreeNode
:rtype: bool
"""
return self.isMirror(root,root)
def isMirror(self,leftTree,rightTree):
if leftTree and rightTree: #都有子树,判断
if leftTree.val==rightTree.val:
flag1=self.isMirror(leftTree.left,rightTree.right)
flag2=self.isMirror(leftTree.right,rightTree.left)
return (flag1 and flag2)
else:
return False
elif not leftTree and not rightTree:#都无子树,正确
return True
else:#一边有一边没有,错误
return False