【Description】
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/
2 2
/ \ /
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/
2 2
\
3 3
Follow up: Solve it both recursively and iteratively.
【Idea】
今天偷懒写个简单的。
递归比较左右节点的右左值即可,递归中发现不对称return False, 对称则继续向下比较,直到叶子节点均为空
【Solution】
# 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 judge(root1, root2):
if not root1 and not root2: # 均null
return True
elif not root1 or not root2:
return False
elif root1.val!=root2.val:
return False
else:
return judge(root1.left, root2.right) and judge(root1.right, root2.left)
if not root:
return True
res = judge(root.left, root.right)
return res