110. Balanced Binary Tree

原文链接:

110. Balanced Binary Tree

读题:

判断是否为平衡二叉树,平衡二叉树的定义是每个节点的左右子树的高度差不超过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 maxDepth(self, root):
        if not root:
            return 0
        return max(self.maxDepth(root.left),self.maxDepth(root.right)) + 1 
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        if not root:
            return True

        lengthL = self.maxDepth(root.left)
        lengthR = self.maxDepth(root.right)
        if lengthL > lengthR + 1 or lengthR > lengthL + 1:
            return False
        else:
            return self.isBalanced(root.left) and self.isBalanced(root.right)

  

原文地址:https://www.cnblogs.com/xqn2017/p/8006846.html