Kth Smallest Element in a BST

Try to solve the Kth Smallest Element in a BST problem.

Statement#

Given the root node of a binary search tree and an integer value k, return the kthk^{th} smallest value in the tree.

Constraints:

  • The number of nodes in the tree is nn.
  • 1kn5001 \leq k \leq n \leq 500
  • 00 \leq Node.data 104\leq 10^4

Examples#

Created with Fabric.js 3.6.6 15 10 20 8 12 16 25 15 10 20 8 12 16 25 15 Sample example 1 Input: Level orderk = 4 The 4th smallest element in the BST is 15.

1 of 2

Created with Fabric.js 3.6.6 15 10 20 8 12 16 25 15 10 20 8 12 16 25 10 Sample example 2 The 2nd smallest element in the BST is 10. Input: Level orderk = 2

2 of 2

Understand the problem#

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Kth Smallest Element in a BST

1

What is the kthk^{th} smallest element when we have the following input?

k = 4

BST:   3  / \ 1   4  \    2
A)

4

B)

1

C)

3

D)

2

Question 1 of 20 attempted

Figure it out!#

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Note: As an additional challenge, we have intentionally hidden the solution to this puzzle.

Drag and drop the cards to rearrange them in the correct sequence.

Start the inorder traversal of the BST.

While traversing the BST, decrement k by 1.

Check if k has reached 00. If it has, return the value of the current node, containing the kthk^{th} smallest element.

Otherwise, continue the traversal of the BST.


Try it yourself#

Implement your solution in main.py in the following coding playground.

We have left the solution to this challenge as an exercise for you. An optimal solution to this problem runs in O(n) time and takes O(n) space. You may try to translate the logic of the solved puzzle into a coded solution.

Python
usercode > main.py
Input #1
Input #2
Kth Smallest Element in a BST

Solution: K Closest Points to Origin

Solution: Kth Smallest Element in a BST