leetcode: 101. Symmetric Tree
阿新 • • 發佈:2018-12-19
Difficulty
Easy.
Problem
# 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
#
# Note:
# Bonus points if you could solve it both recursively and iteratively.
AC
class Solution():
def isSymmetric(self, root):
return self.dfs(root, root)
def dfs(self, p, q):
if not p and not q:
return True
if None in (p, q) or p.val != q.val:
return False
else:
return self.dfs(p.left, q.right) and self.dfs(p.right, q.left)