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)

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券