首页 > 其他 > 详细

面试题 04.04. 检查平衡性

时间:2020-06-08 14:56:15      阅读:50      评论:0      收藏:0      [点我收藏+]

技术分享图片
技术分享图片
技术分享图片

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True

        # 左、右子树深度
        heightLeft = self.treeDepth(root.left)
        heightRight = self.treeDepth(root.right)
        # 判断左、右子树是否平衡
        resultLeft = self.isBalanced(root.left)
        resultRight = self.isBalanced(root.right)

        # 左子树和右子树都是AVL,并且高度相差不大于1,返回真
        if resultLeft and resultRight and abs(heightLeft - heightRight) <= 1:
            return True
        else:
            return False

    # 求二叉树的深度
    def treeDepth(self, root):
        if not root:
            return 0
        depthLeft = self.treeDepth(root.left)
        depthRight = self.treeDepth(root.right)
        return depthLeft + 1 if depthLeft > depthRight else depthRight + 1

面试题 04.04. 检查平衡性

原文:https://www.cnblogs.com/panweiwei/p/13065411.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!