剑指 Offer 28. 对称的二叉树_CodingPark编程公园

对称的二叉树

问题

请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / \
  2   2
 / \ / \
3  4 4  3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3

 

示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true

示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false

链接:https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof


解答

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        def recur(L, R):
            if not L and not R: return True
            if not L or not R or L.val != R.val: return False
            return recur(L.left, R.right) and recur(L.right, R.left)

        return recur(root.left, root.right) if root else True

在这里插入图片描述

有的东西,只有自己写一遍,脑子过一遍,才能知道自己是否真的明白了,才能说自己了解了。
在这里插入图片描述
在这里插入图片描述

二刷时

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
from collections import deque
class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        res = []
        if not root:
            return True
        que = deque()
        que.append(root)
        while que:
            temp = []
            for _ in range(len(que)):
                node = que.popleft()
                if node == 'null':
                    temp.append('null')
                    continue
                temp.append(node.val)
                if node.left:
                    que.append(node.left)
                elif not node.left:
                    que.append('null')

                if node.right:
                    que.append(node.right)
                elif not node.right:
                    que.append('null')
            res.append(temp)

        for i in res[1:]:
            # len(i)->奇数
            if len(i)%2 != 0:
                return False 
            
            # len(i)->偶数
            ping = int(len(i)/2)
            if i[:ping] == i[ping:][::-1]:
                continue
            else:
                return False
        
        return True
 



在这里插入图片描述

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TEAM-AG

编程公园:输出是最好的学习方式

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值