首先需要了解平衡二叉树的性质:
它是一 棵空树或它的左右两个子树的高度差的绝对值不超过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):
if not pRoot:#空树是平衡二叉树
return True
leftHeight = self.countHeight(pRoot.left)+1
rightHeight = self.countHeight(pRoot.right)+1
if abs(leftHeight - rightHeight)>1: #平衡二叉树的左右高度差不大于一
return False
else:
return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
def countHeight(self,pRoot):
if not pRoot:
return 0
return 1+max(self.countHeight(pRoot.left),self.countHeight(pRoot.right))