【剑指Offer】剑指 Offer 55 - II. 平衡二叉树

本文探讨四种不同的方法解决二叉树平衡问题,包括深度优先遍历、依赖递归深度计算、广度优先遍历及深度检查。方法4以最短用时和内存消耗通过全部测试,展示了高效解决平衡判断的技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目
代码
执行用时:56 ms, 在所有 Python3 提交中击败了54.86% 的用户
内存消耗:19.7 MB, 在所有 Python3 提交中击败了35.23% 的用户
通过测试用例:227 / 227

class Solution:
    def isBalanced(self, root: TreeNode) -> bool:
        def height(root):
            if not root:
                return 0
            return max(height(root.left),height(root.right))+1
        if not root:
            return True
        return abs(height(root.left)-height(root.right))<=1 and self.isBalanced(root.left) and self.isBalanced(root.right)

【方法2】
执行用时:60 ms, 在所有 Python3 提交中击败了42.01% 的用户
内存消耗:19.8 MB, 在所有 Python3 提交中击败了19.63% 的用户
通过测试用例:227 / 227

class Solution:
    def dep(self,root):
        if not root:
            return 0
        return max(self.dep(root.left),self.dep(root.right))+1
    def isBalanced(self, root: TreeNode) -> bool:
        if not root:
            return True
        return abs(self.dep(root.left)-self.dep(root.right))<=1 and self.isBalanced(root.left) and self.isBalanced(root.right)

【方法3】
执行用时:64 ms, 在所有 Python3 提交中击败了31.43% 的用户
内存消耗:19.7 MB, 在所有 Python3 提交中击败了53.92% 的用户
通过测试用例:227 / 227

class Solution:
    def dep(self,root):
        if not root:
            return 0
        return max(self.dep(root.left),self.dep(root.right))+1

    def isBalanced(self, root: TreeNode) -> bool:
        queue=[root]
        if not root:return True
        while queue:
            root=queue.pop()
            if abs(self.dep(root.left)-self.dep(root.right))>1:
                return False
            if root.left:
                queue.append(root.left)
            if root.right:
                queue.append(root.right)
        return True

【方法4】
执行用时:36 ms, 在所有 Python3 提交中击败了99.53% 的用户
内存消耗:19.7 MB, 在所有 Python3 提交中击败了48.05% 的用户
通过测试用例:227 / 227

class Solution:
    def depth(self,root):
        if not root:
            return 0
        L=self.depth(root.left)
        R=self.depth(root.right)
        if L==-1 or R==-1 or abs(L-R)>1:
            return -1
        return max(L,R)+1
    def isBalanced(self, root: TreeNode) -> bool:
        return self.isBalanced(root)>=0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值