Top 150 Interview

Balanced Binary Tree

Detailed guide and Python implementation for the 'Balanced Binary Tree' problem.

問題提起

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

A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.

The tree is represented as a level-order list. Implement a function isBalanced(root: list) -> bool.

制約
  • The number of nodes in the tree is in the range [0, 5000]
  • -10000 <= Node.val <= 10000

Example 1
Input
[3,9,20,None,None,15,7]
Output
True
Explanation

The left subtree (rooted at 9) has depth 1, and the right subtree (rooted at 20) has depth 2. The difference is 1, so the tree is balanced.

Example 2
Input
[1,2,2,3,3,None,None,4,4]
Output
False
Explanation

The left subtree has depth 3 while the right subtree has depth 1. The difference is 2, so the tree is not balanced.

Example 3
Input
[]
Output
True
Explanation

An empty tree is considered balanced.

Need a Hint?
Consider using Trees-specific data structures like sets or heaps.
Edge Cases to Watch
  • Empty input structures
  • Single element inputs
  • Large numerical bounds

解決する準備はできましたか?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

エディタで開く
Found this breakdown helpful?

PyRun is built and maintained by an independent solo developer. If this helped your interview prep, consider buying a coffee!

Buy me a coffee

推奨される Python リソース

関連するインタラクティブなチュートリアル、チートシート、コード比較で知識を深めてください。