自底向上的递归
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def height(root):
if not root:
return 0
height_left = height(root.left)
height_right = height(root.right)
if height_left == -1 or height_right == -1 or \
abs(height_left - height_right) > 1:
return -1
else:
return max(height_left, height_right) + 1
return height(root) > -1