Entrevista a los 150 mejoresMedio

Subárbol de otro árbol

Guía detallada e implementación de Python para el problema 'Subárbol de otro árbol'.

Declaración del problema

Medio

Dadas las raíces de dos árboles binarios raíz y subRoot, devuelve verdadero si hay un subárbol de raíz con la misma estructura y valores de nodo de subRoot y falso en caso contrario.

Un subárbol de un árbol binario es un árbol que consta de un nodo en un árbol y todos los descendientes de este nodo. El árbol también podría considerarse como un subárbol de sí mismo.

Los árboles se representan como listas de orden de niveles. Implementar una función isSubtree(root: list, subRoot: list) -> bool.

Restricciones
  • 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

Ejemplos

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?
Considere la posibilidad de utilizar estructuras de datos específicas de Trees, como conjuntos o montones.
Edge Cases to Watch
  • Estructuras de entrada vacías
  • Entradas de un solo elemento
  • Grandes límites numéricos

¿Listo para resolver?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Abrir en el 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

Recursos recomendados de Python

Amplíe sus conocimientos con tutoriales interactivos relacionados, hojas de trucos y comparaciones de códigos.