思路:平衡二叉树的左右子树的深度相差不能超过1, 因此可以利用上一题求二叉树的深度的函数,对左右子树求最大深度,如果深度小于1,那么就是平衡二叉树了
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def IsBalanced_Solution(self, pRoot): # write code here if not pRoot: return True if abs(self.max_depth(pRoot.left) - self.max_depth(pRoot.right)) > 1: return False return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right) def max_depth(self, pRoot): if not pRoot: return 0 return max(self.max_depth(pRoot.left), self.max_depth(pRoot.right)) + 1