150 najlepszych wywiadówŁatwe

K-ty najmniejszy element w BST

Szczegółowy przewodnik i implementacja Python dla problemu „K-ty najmniejszy element w BST”.

Oświadczenie o problemie

Łatwe

Biorąc pod uwagę pierwiastek drzewa poszukiwań binarnych i liczbę całkowitą k, zwróć k-tą najmniejszą wartość (z indeksem 1) ze wszystkich wartości węzłów w drzewie.

Drzewo jest reprezentowane jako lista poziomów. Zaimplementuj funkcję kthSmallest(root: list, k: int) -> int.

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

Przykłady

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?
Rozważ użycie struktur danych specyficznych dla drzew, takich jak zestawy lub sterty.
Edge Cases to Watch
  • Puste struktury wejściowe
  • Wejścia jednoelementowe
  • Duże granice liczbowe

Gotowy do rozwiązania?

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

Otwórz w Edytorze
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

Polecane zasoby Pythona

Poszerzaj swoją wiedzę dzięki powiązanym interaktywnym samouczkom, ściągawkom i porównaniom kodów.