Solution: Kth Smallest Element in a BST

Let's solve the Kth Smallest Element in a BST problem using the Tree Depth-First Search pattern.

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.
  • 1kn1041 \leq k \leq n \leq 10^4
  • 00 \leq Node.data 104\leq 10^4

Solution#

For this solution, we will recursively perform the inorder traversal(left subtree, root, right subtree) on the binary search tree. We will use the inorder traversal to get elements in sorted order.

While performing the inorder traversal on the tree, decrement k by 11, indicating the number of smaller elements that still need to be found. After decrementing k, we check whether the value of k has reached 00. If it is 00, we return the current node, indicating the node having the kthk^{th} smallest element. If not, continue the traversal.

This approach ensures that we traverse the tree in a depth-first manner while appropriately updating k and effectively finding the kthk^{th} smallest element.

Now, let’s look at the following illustration to get a better understanding of the solution:

canvasAnimation-image

1 of 17

canvasAnimation-image

2 of 17

canvasAnimation-image

3 of 17

canvasAnimation-image

4 of 17

canvasAnimation-image

5 of 17

canvasAnimation-image

6 of 17

canvasAnimation-image

7 of 17

canvasAnimation-image

8 of 17

canvasAnimation-image

9 of 17

canvasAnimation-image

10 of 17

canvasAnimation-image

11 of 17

canvasAnimation-image

12 of 17

canvasAnimation-image

13 of 17

canvasAnimation-image

14 of 17

canvasAnimation-image

15 of 17

canvasAnimation-image

16 of 17

canvasAnimation-image

17 of 17

Let’s look at the code for this solution below:

Solution.py
TreeNode.py
BinaryTree.py
Kth Smallest Element in a BST

Time complexity#

The time complexity of this solution is O(n)O(n), where nn represents the number of nodes in the binary tree.

Space complexity#

The space complexity of this solution is O(n)O(n). This is because our recursive algorithm uses space on the call stack.

Kth Smallest Element in a BST

Two Heaps: Introduction