题目描述
方法
1. 从小至上判断子树是否满足平衡
树深度= max(左子树深度,右子树深度) + 1
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
self.res = True
def recur(root):
if not root:
return 0
a = recur(root.left)
b = recur(root.right)
if abs(a - b) >= 2:
self.res = False
return max(a, b) + 1
recur(root)
return self.res
缺点: 有子树不平衡后会继续计算,时间冗余
2. 剪枝判断
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
self.res = True
def recur(root):
if not root:
return 0
a = recur(root.left)
if a == -1:
return -1
b = recur(root.right)
if b == -1:
return -1
if abs(a - b) >= 2:
self.res = False
return -1
return max(a, b) + 1
recur(root)
return self.res