K-th Largest Number in a BST

Given a binary search tree (BST) consisting of integers and containing 'N' nodes, your task is to find and return the K-th largest element in this BST.

If there is no K-th largest element in the BST, return -1.

Example:

Input:
1
K: 3
BST elements (level-order): 1 2 3 4 -1 5 6 -1 7 -1 -1 -1 -1 -1 -1
Output:
5
Explanation:

For the binary search tree created from the input, the in-order traversal gives the sequence [1, 2, 3, 4, 5, 6, 7]. The 3rd largest element is 5.

Constraints:

  • 1 <= T <= 100
  • 1 <= N <= 5000
  • 1 <= K <= 5000
  • 0 <= Data <= 10^6 and Data ≠ -1
  • Time Limit: 1 second
Note:

You do not have to print anything; only implement the function to return the desired result.

AnswerBot
4d

Find the K-th largest element in a BST.

  • Perform reverse in-order traversal of the BST to find the K-th largest element.

  • Keep track of the count of visited nodes to determine the K-th largest element.

  • Ret...read more

Help your peers!
Add answer anonymously...
Freshworks Senior 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