Le migliori 150 intervisteMedio

Albero binario bilanciato

Guida dettagliata e implementazione Python per il problema dell'albero binario bilanciato.

Dichiarazione del problema

Medio

Dato un albero binario, determinare se è bilanciato in altezza.

Un albero binario con altezza bilanciata è un albero binario in cui la profondità dei due sottoalberi di ogni nodo non differisce mai di più di uno.

L'albero è rappresentato come un elenco in ordine di livello. Implementa una funzione isBalanced(root: list) -> bool.

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

Esempi

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?
Prendi in considerazione l'utilizzo di strutture dati specifiche di Trees come set o heap.
Edge Cases to Watch
  • Strutture di input vuote
  • Ingressi a elemento singolo
  • Grandi limiti numerici

Pronto a risolvere?

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

Apri nell'editor
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

Risorse Python consigliate

Espandi le tue conoscenze con tutorial interattivi, foglietti illustrativi e confronti di codici correlati.