【LEETCODE】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 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


你可能感兴趣的:(LeetCode,python)