k-th smallest element in BST
Submissions: 20031   Accuracy:

49.44%

  Difficulty: Medium   Marks: 4
Associated Course(s):   Amazon SDE Test Series

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: 

  1. 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.

  2. For example:
     
    For the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7 N

  3. 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

** For More Input/Output Examples Use 'Expected Output' option **

Contributor: Saksham Raj Seth, Harshit Sidhwa
Author: saksham seth


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.



Need help with your code? Please use ide.geeksforgeeks.org, generate link and share the link here.


to report an issue on this page.