Le migliori 150 intervisteMedio

Sottoalbero di un altro albero

Guida dettagliata e implementazione Python per il problema "Sottoalbero di un altro albero".

Dichiarazione del problema

Medio

Date le radici di due alberi binari root e subRoot, restituisce true se esiste un sottoalbero di root con la stessa struttura e gli stessi valori dei nodi di subRoot e false altrimenti.

Un sottoalbero di un albero binario è un albero costituito da un nodo nell'albero e da tutti i discendenti di questo nodo. L'albero albero potrebbe anche essere considerato come un sottoalbero di se stesso.

Gli alberi sono rappresentati come elenchi in ordine di livello. Implementa una funzione isSubtree(root: list, subRoot: list) -> bool.

Vincoli
  • The number of nodes in the root tree is in the range [1, 2000]
  • The number of nodes in the subRoot tree is in the range [1, 1000]
  • -10000 <= root.val <= 10000
  • -10000 <= subRoot.val <= 10000

Esempi

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

The subtree rooted at node 4 in the main tree matches subRoot exactly.

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

The subtree rooted at 4 in the main tree has an extra node 0 under 2, so it doesn't match subRoot.

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.