AlgoMaster Logo

Kth Smallest Element in a BST

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Inorder Traversal with List

Intuition:

A Binary Search Tree (BST) has the property that an inorder traversal (left-root-right) of the tree gives the nodes in non-decreasing order. By performing an inorder traversal and storing the elements in a list, we can easily access the kth smallest element by retrieving the element at index k-1 from the list.

Code:

2. Inorder Traversal with Counter

Intuition:

By maintaining a counter while doing the inorder traversal, we can stop the traversal as soon as the kth element is found. This avoids storing all elements, thereby saving space.

Code:

3. Iterative Inorder Traversal

Intuition:

We can simulate the recursive inorder traversal using an explicit stack. This allows us to handle trees iteratively, which can be more space efficient in specific scenarios.

Code: