题目描述:
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
解题思路:
平衡二叉树的定义:平衡二叉搜索树(Self-balancing binary search tree)又被称为AVL树(有别于AVL算法),且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过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 pRoot == None:
return True
left_depth = self.GetDepth(pRoot.left)
right_depth = self.GetDepth(pRoot.right)
if abs(left_depth - right_depth) <= 1:
return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
return False
def GetDepth(self, pRoot):
if pRoot == None:
return 0
if pRoot.left == None and pRoot.right == None:
return 1
return 1 + max(self.GetDepth(pRoot.left), self.GetDepth(pRoot.right))