【剑指Offer】39平衡二叉树
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
时间限制:1秒;空间限制:32768K;本题知识点:树
解题思路
需要用到查找二叉树深度的函数,根据平衡二叉树的性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过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
a,b = 0,0
a = self.TreeDepth(pRoot.left)
b = self.TreeDepth(pRoot.right)
return abs(a-b)<=1 and self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
def TreeDepth(self, pRoot):
# write code here
if pRoot == None:
return 0
a,b,c = 0,0,0
if pRoot.left!= None:
a = self.TreeDepth(pRoot.left) + 1
if pRoot.right!= None:
b = self.TreeDepth(pRoot.right) + 1
if pRoot.left==None and pRoot.right== None:
c = 1
return max(a,b,c)