跳到主要内容

Balanced Binary Tree

描述​

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

分析​

无

代码​

# Balanced Binary Tree
# 时间复杂度O(n),空间复杂度O(logn)
class Solution:
def isBalanced(self, root):
return self.balancedHeight(root) >= 0

"""
Returns the height of `root` if `root` is a balanced tree,
otherwise, returns `-1`.
"""
def balancedHeight(self, root):
if root is None: return 0 # 终止条件

left = self.balancedHeight(root.left)
right = self.balancedHeight(root.right)

if left < 0 or right < 0 or abs(left - right) > 1: return -1 # 剪枝

return max(left, right) + 1 # 三方合并