思路,递归 平衡二叉树就是左右子树的高度差不超过1,与此同时,子节点的左右子树的高度差也不超过1。所以,先判断根节点的左右子树符不符合平衡二叉树的要求,如果符合,则递归判断左右子树是否也都符合,如果不符合,直接返回False

# -*- 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
        left = self.depth(pRoot.left)
        right = self.depth(pRoot.right)
        if abs(left-right)>1:
            return False
        return all([self.IsBalanced_Solution(pRoot.left),self.IsBalanced_Solution(pRoot.right)])
    def depth(self,pRoot):
        if not pRoot:
            return 0
        left = right = 0
        if pRoot.left:
            left = self.depth(pRoot.left)
        if pRoot.right:
            right = self.depth(pRoot.right)
        return max([left,right])+1