Tutorialspoint
Problem
Solution
Submissions

Kth Smallest Element in a BST

Certification: Intermediate Level Accuracy: 0% Submissions: 0 Points: 12

Write a C# program to implement the KthSmallest function, which finds the kth smallest element in a Binary Search Tree (BST). The function should take the root of a BST and an integer k, and return the kth smallest element in the tree.

Example 1
  • Input: root = [3,1,4,null,2], k = 1
  • Output: 1
  • Explanation:
    • Tree structure:
      3
       / \
      1 4
       \
      2
    • The smallest element in this BST is 1.
Example 2
  • Input: root = [5,3,6,2,4,null,null,1], k = 3
  • Output: 3
  • Explanation:
    • Tree structure:
      5
       / \
      36
       / \
      2 4
      /
      1
    • The elements in ascending order are [1,2,3,4,5,6] and the 3rd element is 3.
Constraints
  • The number of nodes in the tree is n, where 1 ≤ n ≤ 10^4
  • 0 ≤ Node.val ≤ 10^4
  • 1 ≤ k ≤ n
  • Time Complexity: O(h + k) where h is the height of the tree
  • Space Complexity: O(h) for recursion stack
TreeGoldman SachsSwiggy
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use an in-order traversal to visit nodes in ascending order
  • Keep a counter to track the position of the current node
  • When the counter equals k, you've found the kth smallest element
  • Try both recursive and iterative solutions
  • Optimize by stopping the traversal once the kth element is found

Steps to solve by this approach:

 Step 1: Implement an in-order traversal using a stack (iterative approach)
 Step 2: Initialize a counter to keep track of the number of nodes visited
 Step 3: Push all left nodes onto the stack first (following BST property that left subtree contains smaller values)
 Step 4: Process nodes in the stack one by one, incrementing the counter for each node
 Step 5: When the counter equals k, return the value of the current node as the kth smallest
 Step 6: If the current node has a right child, traverse its left subtree next
 Step 7: Continue this process until either the kth element is found or all nodes are visited

Submitted Code :