题目:力扣
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def compare(left, right):
if not (left or right):
return True
if not (left and right):
return False
if left.val != right.val:
return False
res = compare(left.left, right.right) and compare(left.right, right.left)
return res
res = compare(root.left, root.right)
return res