Leetcode 101. 对称二叉树

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [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

说明:

如果你可以运用递归和迭代两种方法解决这个问题,会很加分。

tips: 二叉树的问题基本上都可以用递归去做,对称二叉树只需要判断左子树的左节点和右子树的右节点记忆左子树的右节点和右子树的左节点是否一致。

递归代码:

    def isSymmetric(self, root: TreeNode) -> bool:
        def dg(root1,root2):
            if (not root1 and root2) or (not root2 and root1):
                return False
            if not root1 and not root2:
                return True
            if  root1.val!=root2.val:
                return False
            return dg(root1.left,root2.right) and dg(root1.right,root2.left)
        return dg(root,root)

按层次遍历代码:

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        def bfs(root):
            if not root:
                return True
            queue=[root]
            res=[]
            now,last=root,root
            while queue:
                pop=queue.pop()
                res.append(pop.val)
                if pop.left:
                    queue.insert(0,pop.left)
                else:
                    queue.insert(0,TreeNode(-9999))
                if pop.right:
                    queue.insert(0,pop.right)
                else:
                    queue.insert(0,TreeNode(-9999))
                    
                now=queue[0]
                if pop == last:
                    last=now
                    if res!=res[::-1]:
                        return False
                    
                    cnt=0
                    for r in res:
                        if r==-9999:
                            cnt+=1
                    if cnt==len(res):
                        return True
                    res=[]
        return bfs(root)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值