【LEETCODE】110-Balanced Binary Tree

来源:互联网 发布:js检测ie浏览器版本 编辑:程序博客网 时间:2024/05/16 23:33

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees ofevery node never differ by more than 1.


# Definition for a binary tree node.# class TreeNode(object):#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution(object):        def getDepth(self,root):                #先写一个获得深度的函数                   #depth = 0        if root is None:            return 0        else:            #depth +=1            return max(self.getDepth(root.left),self.getDepth(root.right))+1                    def isBalanced(self, root):        """        :type root: TreeNode        :rtype: bool        """                if root is None:            return True        elif abs(self.getDepth(root.left)-self.getDepth(root.right))<=1:            #当前node的左子树的depth与右子树的depth之差<=1时            return self.isBalanced(root.left) and self.isBalanced(root.right)       #则递归继续判断左右子树        else:            return False


0 0