K-th Smallest Element in BST
Your task is to find the ‘K-th’ smallest element in a given Binary Search Tree (BST).
Explanation:
A Binary Search Tree is a binary tree in which for each node, all elements in the left subtree of a node are smaller, and all elements in the right subtree are larger.
Input:
The input begins with an integer ‘T’ representing the number of test cases.
Each test case consists of two parts:
1. An integer ‘K’.
2. A single line containing the elements of the tree in level order format, with node values separated by spaces. '-1' represents a null node.
Output:
For each test case, output the K-th smallest element in the BST. If the K-th smallest element does not exist, return -1.
Example:
Input:
1
3
4 2 7 -1 -1 5 8 -1 -1 -1 -1
Output:
5
Constraints:
- 1 <= T <= 100
- 1 <= N, K <= 3000
- -10^9 <= data <= 10^9
Note:
1. Implement the function to determine the K-th smallest element. No need to print outputs explicitly.
2. Focus is on returning the value of the K-th smallest node, not the node itself.
3. Inputs may include '-1' to denote the absence of a node in certain positions.
Be the first one to answer
Add answer anonymously...
Top ServiceNow Software Engineer interview questions & answers
Popular interview questions of Software Engineer
Top HR questions asked in ServiceNow Software Engineer
Stay ahead in your career. Get AmbitionBox app
Helping over 1 Crore job seekers every month in choosing their right fit company
65 L+
Reviews
4 L+
Interviews
4 Cr+
Salaries
1 Cr+
Users/Month
Contribute to help millions
Get AmbitionBox app