给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。
样例
给出二叉树 A={3,9,20,#,#,15,7}
, B={3,#,20,15,7}
A) 3 B) 3 / \ \ 9 20 20 / \ / \ 15 7 15 7
二叉树A是高度平衡的二叉树,但是B不是
这个题首先写一个算二叉树最大深度的函数,然后用递归算就行了
def prehandle(self,root):
if root == None:
return 0
lh = self.prehandle(root.left)
rh = self.prehandle(root.right)
if lh > rh:
return lh + 1
else:
return rh + 1
def isBalanced(self, root):
if root == None:
return True
lh = self.prehandle(root.left)
rh = self.prehandle(root.right)
if lh - rh > 1 or lh - rh < -1:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)