Given a BST and an integer K. Find the Kth Smallest element in the BST.
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 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
For each test case, the output will be the kth smallest element of BST. If no such element exists then print -1.
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).
Example(To be used only for expected output):
2 1 3
2 1 3
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.