首页 > 其他 > 详细

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

时间:2020-09-13 17:14:45      阅读:55      评论:0      收藏:0      [点我收藏+]

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

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True
        # 求左子树深度
        leftDenth = self.treeDepth(root.left)
        rightDenth = self.treeDepth(root.right)
        resLeft = self.isBalanced(root.left)
        resRight = self.isBalanced(root.right)
        if resLeft and resRight and abs(leftDenth-rightDenth)<=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

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

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

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