【题目描述】
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
【解题思路】
平衡二叉树:平衡二叉树(Balanced Binary Tree)具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
一种直观的思路是采用双重递归,第一层递归是判定该节点及其左右子树是否都是平衡二叉树,第二层递归是计算该节点的左右子树的深度,用Python实现的代码如下:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def TreeDepth(self,pRoot):
if pRoot == None:
return 0
return max(self.TreeDepth(pRoot.left), self.TreeDepth(pRoot.right)) + 1
def IsBalanced_Solution(self, pRoot):
# write code here
if pRoot == None:
return True
else:
left_depth = self.TreeDepth(pRoot.left)
right_depth = self.TreeDepth(pRoot.right)
return abs(left_depth - right_depth)<=1 and self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
但是上述方法由于是双重递归,所以有很多不必要的计算,比如该子树已经不是平衡二叉树了,却还是会在后续的计算中继续计算其深度。为此,使用剪枝的方法:在递归计算树的深度的过程中,如果左子树和右子树的深度绝对值超过1,则返回-1,也就是将此不满足条件的子树的深度赋值为1,则在后续的计算中,若出现了深度为1的情况,就直接可判定不满足条件,直接返回-1即可。用Python实现的代码如下:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def TreeDepth(self,pRoot):
if pRoot == None:
return 0
left_depth = self.TreeDepth(pRoot.left)
if left_depth == -1:
return -1
right_depth = self.TreeDepth(pRoot.right)
if right_depth == -1:
return -1
if abs(left_depth - right_depth)<=1 :
return 1 + max(left_depth, right_depth)
else:
return -1
def IsBalanced_Solution(self, pRoot):
# write code here
if self.TreeDepth(pRoot) == -1:
return False
else:
return True