Le migliori 150 intervisteMedio

Stesso albero binario

Guida dettagliata e implementazione Python per il problema "Same Binary Tree".

Dichiarazione del problema

Medio

Date le radici di due alberi binari p e q, scrivi una funzione per verificare se sono uguali o meno.

Due alberi binari sono considerati uguali se sono strutturalmente identici e i nodi hanno lo stesso valore.

Gli alberi sono rappresentati come elenchi in ordine di livello. Implementa una funzione isSameTree(p: list, q: list) -> bool.

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

Esempi

Example 1
Input
[1,2,3], [1,2,3]
Output
True
Explanation

Both trees have the same structure and values.

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

In the first tree, 2 is the left child. In the second tree, 2 is the right child. Different structures.

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

Same structure but different values at the children.

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.