链接:https://leetcode.cn/problems/check-balance-lcci/
实现一个函数,检查二叉树是否平衡。在这个问题中,平衡树的定义如下:任意一个节点,其两棵子树的高度差不超过 1。
示例 1:
给定二叉树 [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回 true 。
示例 2:
给定二叉树 [1,2,2,3,3,null,null,4,4]
1
/ \
2 2
/ \
3 3
/ \
4 4
返回 false 。
分治法
采用返回多个值的分治,(hegiht, is_balance)。
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def devide_conquer(root):
if not root:
return (0, True)
l_height, l_balance = devide_conquer(root.left)
r_height, r_balance = devide_conquer(root.right)
if abs(l_height - r_height) < 2 and l_balance and r_balance:
return (max(l_height, r_height) + 1, True)
return (-1, False) # 此时高度是多少已经不重要
_, balance = devide(root)
return balance