Le migliori 150 intervisteFacile

K-esimo elemento più piccolo nella BST

Guida dettagliata e implementazione Python per il problema "Kth Smallest Element In BST".

Dichiarazione del problema

Facile

Data la radice di un albero di ricerca binario e un intero k, restituisce il kesimo valore più piccolo (indicizzato in 1) di tutti i valori dei nodi nell'albero.

L'albero è rappresentato come un elenco in ordine di livello. Implementa una funzione kthSmallest(root: list, k: int) -> int.

Vincoli
  • The number of nodes in the tree is n
  • 1 <= k <= n <= 10000
  • 0 <= Node.val <= 10000

Esempi

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

The in-order traversal is [1,2,3,4]. The 1st smallest is 1.

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

The in-order traversal is [1,2,3,4,5,6]. The 3rd smallest is 3.

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.