[Geeks for Geeks] k-th smallest element in BST

k-th smallest element in BST

Given a BST and an integer K. Find the Kth Smallest element in the BST.

  • Time : O(k)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
int res = -1;
void travel(struct Node* node, int k, int& counter) {
if(!node) return;
if(counter > k) return;
travel(node->left, k, counter);
if(k == counter) res = node->data;
counter++;
travel(node->right, k, counter);
}

public:
// Return the Kth smallest element in the given BST
int KthSmallestElement(Node *root, int K) {
res = -1;
int counter = 1;
travel(root, K, counter);
return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/22/PS/GeeksforGeeks/find-k-th-smallest-element-in-bst/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.