leetcode: 101. Symmetric Tree

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)
发布了599 篇原创文章 · 获赞 856 · 访问量 184万+

猜你喜欢

转载自blog.csdn.net/JNingWei/article/details/83751969