Sezione DSAMedio

Albero binario

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

Dichiarazione del problema

Medio

Scrivi una funzione is_univalued_binary_tree(tree_arr) che accetta una rappresentazione array di un albero binario tree_arr (dove la radice è nell'indice 0 e i figli dell'indice i sono in 2i + 1 e 2i + 2, con None che rappresenta i nodi vuoti) e restituisce True se ogni nodo nell'albero ha lo stesso valore, oppure False altrimenti.

Vincoli
  • 0 <= len(tree_arr) <= 1000

Esempi

Example 1
Input
tree_arr = [1, 1, 1, 1, 1, None, 1]
Output
True
Explanation

All nodes in the tree contain the value 1.

Example 2
Input
tree_arr = [2, 2, 2, 5, 2]
Output
False
Explanation

One node has value 5, which differs from other nodes (value 2).

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.