两种解法,递归(dfs)和队列(广度)
递归,看了官方题解:
# 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(p,q):
if not p and not q:
return True
if not p or not q:
return False
if p.val == q.val and check(p.left,q.right) and check(p.right,q.left):
return True
return check(root,root)
队列:(这又是看了题解区负雪明烛的解答)
# 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:
queue = collections.deque()
queue.append((root, root))
while queue:
p, q = queue.popleft()
if not p and not q:
continue
if not p or not q:
return False
if p.val != q.val:
return False
queue.append((p.left, q.right))
queue.append((p.right, q.left))
return True