平衡二叉树左右子树高度差不超过 1。
解题思路
如果二叉树的每个节点的左子树和右子树的深度不大于1,它就是平衡二叉树。先写一个求深度的函数,再对每一个节点判断,看该节点的左子树的深度和右子树的深度的差是否大于1
class Solution:
def IsBalanced_Solution(self, pRoot):
# write code here
def depth(proot):
if not proot:
return 0
return 1+max(depth(proot.left),depth(proot.right))
if not pRoot:
return True
l = depth(pRoot.left)
r = depth(pRoot.right)
if abs(l-r)<=1:
return self.IsBalanced_Solution(pRoot.left)\
and self.IsBalanced_Solution(pRoot.right)
return False