Skip to content

Commit 973f48c

Browse files
committed
k-th smallest element in BST
1 parent 9b00790 commit 973f48c

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

DSA Crack Sheet/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,7 @@
212212
- [Convert a normal BST to Balanced BST](https://www.geeksforgeeks.org/convert-normal-bst-balanced-bst/ "view topic")
213213
- [Merge Two Balanced Binary Search Trees](https://www.geeksforgeeks.org/merge-two-balanced-binary-search-trees/ "view post")
214214
- [Kth largest element in BST](https://practice.geeksforgeeks.org/problems/kth-largest-element-in-bst/1# "view question") - [Cpp Solution](./solutions/Kth%20largest%20element%20in%20BST.cpp)
215+
- [k-th smallest element in BST](https://practice.geeksforgeeks.org/problems/find-k-th-smallest-element-in-bst/1 "view question") - [Cpp Solution](./solutions/k-th%20smallest%20element%20in%20BST.cpp)
215216
- []( "view question") - [Cpp Solution](./solutions/.cpp)
216217

217218
### Greedy Method
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
k-th smallest element in BST
3+
============================
4+
5+
Given a BST and an integer K. Find the Kth Smallest element in the BST.
6+
7+
Example 1:
8+
Input:
9+
2
10+
/ \
11+
1 3
12+
K = 2
13+
Output: 2
14+
15+
Example 2:
16+
Input:
17+
2
18+
/ \
19+
1 3
20+
K = 5
21+
Output: -1
22+
23+
24+
Your Task:
25+
You don't need to read input or print anything. Your task is to complete the function KthSmallestElement() which takes the root of the BST and integer K as inputs and return the Kth smallest element in the BST, if no such element exists return -1.
26+
27+
Expected Time Complexity: O(N).
28+
Expected Auxiliary Space: O(1).
29+
30+
Constraints:
31+
1<=Number of nodes<=100000
32+
*/
33+
34+
int ans = -1;
35+
void inorder(Node *root, int &k)
36+
{
37+
if (k == 0 || !root)
38+
return;
39+
inorder(root->left, k);
40+
k--;
41+
if (k == 0)
42+
{
43+
ans = root->data;
44+
return;
45+
}
46+
inorder(root->right, k);
47+
}
48+
49+
// Return the Kth smallest element in the given BST
50+
int KthSmallestElement(Node *root, int K)
51+
{
52+
//add code here.
53+
inorder(root, K);
54+
return ans;
55+
}

0 commit comments

Comments
 (0)