Le migliori 150 intervisteDifficile

Profondità massima dell'albero binario

Guida dettagliata e implementazione Python per il problema della "profondità massima dell'albero binario".

Dichiarazione del problema

Difficile

Data la radice di un albero binario, restituisce la sua profondità massima.

La profondità massima di un albero binario è il numero di nodi lungo il percorso più lungo dal nodo radice fino al nodo foglia più lontano.

L'albero è rappresentato come un elenco in ordine di livello dove Nessuno rappresenta un nodo mancante. Implementa una funzione maxDepth(root: list) -> int.

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

Esempi

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

The tree has 3 levels: root [3], second level [9,20], third level [15,7]. The longest path is 3->20->15 or 3->20->7, both of depth 3.

Example 2
Input
[1,None,2]
Output
2
Explanation

The tree has root 1 with only a right child 2. Depth is 2.

Example 3
Input
[]
Output
0
Explanation

An empty tree has depth 0.

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.