简繁EN

LeetCodeNo. 029

[LeetCode with Python] 110. Balanced Binary Tree

Contents

Problem

Problem page: https://leetcode.com/problems/balanced-binary-tree/
Topics: Tree, Depth-first Search
Difficulty: Easy
Similar problems: (E) Maximum Depth of 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.


Analysis

Check whether a tree is height-balanced, meaning the heights of the left and right subtrees at each node differ by at most 1. See the definition of a balanced binary tree (BBT) or an AVL tree. Once again, I use the usual recursive backtracking approach for binary trees.


Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution:
def checkBBT(self, root):
if None == root:
return True, 0
isLeftBBT, leftDepth = self.checkBBT(root.left)
isRightBBT, rightDepth = self.checkBBT(root.right)
isBBT = isLeftBBT and isRightBBT and abs(leftDepth - rightDepth) <= 1
depth = max(leftDepth, rightDepth) + 1
return isBBT, depth

# @param root, a tree node
# @return a boolean
def isBalanced(self, root):
return self.checkBBT(root)[0]

Article link: https://xnerv.wang/en/leetcode-balanced-binary-tree/