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
4mo

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!
Select
Add answer anonymously...

Freshworks Senior Software Engineer interview questions & answers

A Senior Software Engineer was asked 7mo agoQ. Implement a debounce function.
A Senior Software Engineer was asked Q. Given a Binary Search Tree (BST), find the kth largest element.
A Senior Software Engineer was asked Q. Given an array of integers, find the number of pairs whose sum is a perfect squa...read more

Popular interview questions of Senior Software Engineer

A Senior Software Engineer was asked 7mo agoQ1. Implement a debounce function.
A Senior Software Engineer was asked Q2. Given a Binary Search Tree (BST), find the kth largest element.
A Senior Software Engineer was asked Q3. Given an array of integers, find the number of pairs whose sum is a perfect squa...read more
Freshworks Senior Software Engineer Interview Questions
Stay ahead in your career. Get AmbitionBox app
play-icon
play-icon
qr-code
Trusted by over 1.5 Crore job seekers to find their right fit company
80 L+

Reviews

10L+

Interviews

4 Cr+

Salaries

1.5 Cr+

Users

Contribute to help millions

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

Follow Us
  • Youtube
  • Instagram
  • LinkedIn
  • Facebook
  • Twitter
Profile Image
Hello, Guest
AmbitionBox Employee Choice Awards 2025
Winners announced!
awards-icon
Contribute to help millions!
Write a review
Write a review
Share interview
Share interview
Contribute salary
Contribute salary
Add office photos
Add office photos
Add office benefits
Add office benefits