https://www.geeksforgeeks.org/batch/gfg-160-problems/track/tree-gfg-160/problem/find-k-th-smallest-element-in-bst
class Solution {
public:
// Return the Kth smallest element in the given BST
int kthSmallest(Node *root, int k) {
// add code here.
int count =0 ;
int res = -1;
helper(root , k , count , res);
return res;
}
private:
void helper(Node *root, int k , int & count , int & res){
if(!root) return;
helper(root->left , k , count , res);
count++;
if(count == k) {
res = root->data;
return;
}
helper(root->right , k , count , res);
}
};
⚙️ Time and Space Complexity
- Time Complexity:
- Average case: O(H + k) where H is the height of the tree.
- Worst case (unbalanced tree): O(n)
- Space Complexity: O(H) for the recursive stack (H = height of tree)