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...
ServiceNow Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
qr-code
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

Made with ❤️ in India. Trademarks belong to their respective owners. All rights reserved © 2024 Info Edge (India) Ltd.

Follow us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter