Le migliori 150 intervisteMedio

Diametro dell'albero binario

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

Dichiarazione del problema

Medio

Data la radice di un albero binario, restituisce la lunghezza del diametro dell'albero.

Il diametro di un albero binario è la lunghezza del percorso più lungo tra due nodi qualsiasi di un albero. Questo percorso può o meno passare attraverso la radice.

La lunghezza di un percorso tra due nodi è rappresentata dal numero di archi tra di loro.

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

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

Esempi

Example 1
Input
[1,2,3,4,5]
Output
3
Explanation

The longest path is 4->2->1->3 or 5->2->1->3, which has 3 edges.

Example 2
Input
[1,2]
Output
1
Explanation

The longest path is 2->1, which has 1 edge.

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.