面试题 04.04. 检查平衡性
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
# 左、右子树深度
heightLeft = self.treeDepth(root.left)
heightRight = self.treeDepth(root.right)
# 判断左、右子树是否平衡
resultLeft = self.isBalanced(root.left)
resultRight = self.isBalanced(root.right)
# 左子树和右子树都是AVL,并且高度相差不大于1,返回真
if resultLeft and resultRight and abs(heightLeft - heightRight) <= 1:
return True
else:
return False
# 求二叉树的深度
def treeDepth(self, root):
if not root:
return 0
depthLeft = self.treeDepth(root.left)
depthRight = self.treeDepth(root.right)
return depthLeft + 1 if depthLeft > depthRight else depthRight + 1