思路:
判断是否是平衡二叉树,即判断任何一个节点的左子树和右子树的高度差的绝对值小于等于1。最直接的做法,遍历每个结点,借助一个获取树深度的递归函数,根据该结点的左右子树高度差判断是否平衡,然后递归地对左右子树进行判断。
# 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
if abs(self.TreeDepth(pRoot.left)-self.TreeDepth(pRoot.right)) > 1:
return False
return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
def TreeDepth(self, pRoot):
# write code here
if pRoot == None:
return 0
nLeft = self.TreeDepth(pRoot.left)
nRight = self.TreeDepth(pRoot.right)
return max(nLeft+1,nRight+1)