Le migliori 150 intervisteFacile

Antenato comune più basso della BST

Guida dettagliata e implementazione Python per il problema dell'"Antenato comune più basso della BST".

Dichiarazione del problema

Facile

Dato un albero di ricerca binario (BST), trova il nodo dell'antenato comune più basso (LCA) di due nodi dati nel BST.

Secondo la definizione di LCA: "L'antenato comune più basso è definito tra due nodi p e q come il nodo più basso in T che ha sia p che q come discendenti (dove permettiamo a un nodo di essere un discendente di se stesso)."

Il BST è rappresentato come un elenco di livelli. Implementare una funzione lowestCommonAncestor(root: list, p: int, q: int) -> int che restituisca il valore del nodo LCA.

Vincoli
  • The number of nodes in the tree is in the range [2, 100000]
  • -1000000000 <= Node.val <= 1000000000
  • All Node.val are unique
  • p != q
  • p and q will exist in the BST

Esempi

Example 1
Input
[6,2,8,0,4,7,9,None,None,3,5], 2, 8
Output
6
Explanation

The LCA of nodes 2 and 8 is 6, which is the root.

Example 2
Input
[6,2,8,0,4,7,9,None,None,3,5], 2, 4
Output
2
Explanation

The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself.

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

The LCA of nodes 2 and 1 is 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.