题解 | #判断是不是平衡二叉树#

判断是不是平衡二叉树

https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222

python3,递归
class Solution:
    def IsBalanced_Solution(self , pRoot: TreeNode) -> bool:
        def depth(root):
            if not root: return 0
            a = 1 + depth(root.left)
            b = 1 + depth(root.right)
            return max(a, b)
        # 空树返回True。各个子树只要有深度差大于1/小于-1的,返回False。否则(and连接)返回True。
        return bool(not pRoot) or ((False if ((depth(pRoot.left) - depth(pRoot.right)) > 1 or (depth(pRoot.left) - depth(pRoot.right)) < -1)  else True) and self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right))


全部评论

相关推荐

这是什么操作什么意思,这公司我服了...
斯派克spark:意思是有比你更便宜的牛马了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务