力扣官方题解:https://leetcode-cn.com/problems/balanced-binary-tree/solution/ping-heng-er-cha-shu-by-leetcode-solution/
解题方法:递归
大函数是遍历左右子树比较大小
abs(height(root.left) - height(root.right))<= 1 (求树与子树之间的差值)
and self.isBalanced(root.left) and self.isBalanced(root.right) (递归左右子树)
小函数是求解树的深度
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def height(root): # 递归遍历树的深度
if not root:
return 0
return max(height(root.left), height(root.right)) + 1
if not root:
return True
return abs(height(root.left) - height(root.right))<= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)
# 求差值and递归遍历左右子树