Search⌘ K
AI Features

Kth Smallest Element in a BST

Explore how to locate the kth smallest element in a binary search tree by applying depth-first search techniques. This lesson helps you understand the problem constraints and guides you to develop an optimal solution using tree traversal and space-time complexity considerations.

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

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


1 / 2

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.

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

1
2
3
4

Try it yourself

Implement your solution in Solution.java 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.

Java
usercode > Solution.java
// Definiton of a binary tree node class
// class TreeNode<T> {
// T data;
// TreeNode<T> left;
// TreeNode<T> right;
// TreeNode(T data) {
// this.data = data;
// this.left = null;
// this.right = null;
// }
// }
import java.util.*;
import ds_v1.BinaryTree.TreeNode;
public class Solution{
public static int kthSmallestElement(TreeNode<Integer> root, int k) {
// Replace this placeholder return statement with your code
return -1;
}
}
Kth Smallest Element in a BST