leetcode:101対称ツリー

困難

簡単。

問題

# 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.

交流

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