Given a BST and an integer K. Find the Kth Smallest element in the BST.
Input:
The first line of input contains the number of test cases T. For each test case, there will two lines. The first line of input is a string representing the tree as described below:
The values in the string are in the order of level order traversal of the tree where, numbers denote node values, and a character “N” denotes NULL child.
For example:
For the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7 N
Second-line is an integer represents K
Output:
For each test case, the output will be the kth smallest element of BST. If no such element exists then print -1.
Your Task:
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.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(1).
Constraints:
1<=T<=10
1<=N<=100000
Example(To be used only for expected output):
Input:
2
2 1 3
2
2 1 3
5
Output:
2
-1
If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.
praneethmamidala83 | 583 |
pallavimanukonda8 | 563 |
a8haysingh | 451 |
vraamg | 432 |
RajatGarg5 | 386 |
descifrador | 1683 |
mantu_singh | 1504 |
rishabh2017 | 1263 |
gladiator121 | 1224 |
kid_kb | 1205 |
blackshadows | 5362 |
Ibrahim Nash | 5244 |
akhayrutdinov | 5111 |
mb1973 | 4974 |
Quandray | 4720 |