牛客-剑指offer系列题解:对称的二叉树

记录刷题的过程。牛客和力扣中都有相关题目,这里以牛客的题目描述为主。该系列默认采用python语言。

1、问题描述:
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

2、所用数据结构:

3、题解:
递归,镜像。画出一颗二叉树,把数据认为是一个镜像。如:[2,1,1,5,3,3,5]即是对称的。

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        #递归,镜像
        def isMirror(t1, t2):
            if t1 == None and t2 == None:
                return True
            if t1 == None or t2 == None:
                return False
            return (t1.val == t2.val) and isMirror(t1.right, t2.left) and isMirror(t1.left, t2.right)

        return isMirror(root, root)
发布了61 篇原创文章 · 获赞 10 · 访问量 2914

猜你喜欢

转载自blog.csdn.net/weixin_42042056/article/details/105513942