题目
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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
进阶:
你可以运用递归和迭代两种方法解决这个问题吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/symmetric-tree
代码
递归求解
# 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:
def check(l,r):
if l is None and r is None:
return True
if l is None or r is None:
return False
return l.val == r.val and check(l.left,r.right) and check(l.right,r.left)
return check(root,root)