题目
一棵树的任意节点,左右子树的深度差值不大于1,为平衡二叉树。判断是否是平衡二叉树。
思路
如果对每个节点的左右子树都调用获取深度的递归子函数,再判断差值,这样,计算到上层节点时,会重复计算下层节点的深度。
改进的方法是,一次后序遍历整个二叉树,递归从下到上返回左右子树的深度时,判断差值,如果大于1直接返回-1。因此在获得深度时,如果等于-1说明已经不平衡了,就返回-1给上层函数。 如果不大于1返回左右子树深度最大值加一。
函数最终的返回值为-1或者是树的深度,不为-1就是平衡的。
代码
class Solution:
def IsBalanced_Solution(self, p):
if p is None:
return True
left = self.depth(p.left)
right = self.depth(p.right)
return abs(left - right) <=1 and self.IsBalanced_Solution(p.left) and self.IsBalanced_Solution(p.right)
def depth(self, p):
if p is None:
return 0
return 1 + max(self.depth(p.left), self.depth(p.right))
class solution:
def IsBalanced(self,pRoot):
def getdepth(pRoot):
if pRoot == None:
return 0
left = getdepth(pRoot.left)
if left == -1:
return -1
right = getdepth(pRoot.right)
if right == -1:
return -1
if abs(left-right) > 1: # 不平衡剪枝
return -1
return max(left,right)+1
return getdepth(pRoot) != -1