Given a binary tree, determine if it is height-balanced.
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
return abs(self.depth(root.left)-self.depth(root.right))<2 and self.isBalanced(root.left) and self.isBalanced(root.right)
def depth(self, root):
if not root:
return 0
return 1+max(self.depth(root.left), self.depth(root.right))
1 需要另外定义一个函数计算每一个node的深度,这个深度也是用递归方法实现的,root的深度等于1+max(左子树深度,右子树深度)
2 判断是否是平衡的,先判断root.left和root.right是否平衡,还得同时判断isBalanced(root.left)和isBalanced(root.right)