给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,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: TreeNode) -> bool:
if not root:
return True
que1=[]
que2=[]
que1.append(root.left)
que2.append(root.right)
while que1 and que2:
p1=que1.pop(0)
p2=que2.pop(0)
if not p1 and not p2:
continue
if not p1 or not p2:
return False
if p1.val!=p2.val:
return False
que1.append(p1.left)
que1.append(p1.right)
que2.append(p2.right)
que2.append(p2.left)
return True
再来递归:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def compare(self,p1,p2):
if not p1 and not p2:
return True
if not p1 or not p2:
return False
if p1.val==p2.val:
return self.compare(p1.left,p2.right)and self.compare(p1.right,p2.left)
else:
return False
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
return self.compare(root.left,root.right)
思路其实并不难,迭代就是对称放入,从头取出,进行比较。
当然这里也可以直接用队列:due=deque([root.left,root.right])
递归就是对称传递,然后比较。