110. Balanced Binary Tree

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 of every 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 = None

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        f,d=self.balance(root)
        return f
    def balance(self,root):
        if root==None:
            return True,0
        l,dl=self.balance(root.left)
        r,dr=self.balance(root.right)
        if l and r:
            diff=dl-dr
            if diff<=1 and diff>=-1:
                depth=1+(dl if dl>dr else dr)
                return True,depth
        return False,-1


你可能感兴趣的:(110. Balanced Binary Tree)