思路:
1、判断当前节点是否平衡:左右子树高度之差小于等于1
2、递归判断全部节点是否平衡
class Solution:
def IsBalanced_Solution(self , pRoot: TreeNode) -> bool:
return self.check(pRoot)
def check(self, p):
if not p:
return True
left = self.getHigh(p.left)
right = self.getHigh(p.right)
return abs(left - right) <= 1 and self.check(p.left) and self.check(p.right)
def getHigh(self, p):
if not p:
return 0
left = self.getHigh(p.left)
right = self.getHigh(p.right)
return max(left, right) + 1