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

判断是不是平衡二叉树

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

''' 判断条件:1)空跟点为True 2)左右子树的深度差<=1

所以:1) if pRoot is None: return True 2)定义二叉树深度函数 左右子树分别递归该函数,判断深度差即可

'''

-- coding:utf-8 --

class TreeNode:

def init(self, x):

self.val = x

self.left = None

self.right = None

class Solution: def IsBalanced_Solution(self, pRoot): # write code here if pRoot is None: return True

    def depth(self,pRoot):
        if pRoot is None:
            return 0
        left=depth(self, pRoot.left)
        right=depth(self,pRoot.right)
        return max(left,right)+1
    left_depth=depth(self, pRoot.left)
    right_depth=depth(self, pRoot.right)
    
    if abs(left_depth-right_depth)>1:
        return False
    
    return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
    
        
    
全部评论

相关推荐

想踩缝纫机的小师弟练...:不理解你们这些人,要放记录就把对方公司名字放出来啊。不然怎么网暴他们
点赞 评论 收藏
分享
我已急😭:这科软不就是可以拿钱买吗?我记得那一年一个学校买狠了,数学排名比北大高。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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