给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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
方法1:递归
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
def check(p: TreeNode, q: TreeNode):
if not p and not q:
return True
if not p or not q:
return False
return p.val == q.val and check(p.left,q.right) and check(p.right,q.left)
return check(root,root)
方法2:迭代
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
queue = [root,root]
while queue:
one,another = queue.pop(),queue.pop()
if not one and not another:
continue
if not one or not another or one.val != another.val:
return False
queue += [one.left,another.right,one.right,another.left]
return True