Timer is Running

Kth largest element in BST
Submissions: 22391   Accuracy:


  Difficulty: Easy   Marks: 2

Given a Binary search tree. Your task is to complete the function which will return the Kth largest element without doing any modification in Binary Search Tree.

First line of input contains the number of test cases T. For each test case, there will be only two line of input, first line contains a string representing the tree as described below: 

  1. The values in the string are in the order of level order traversal of the tree where, numbers denotes node values, and a character “N” denotes NULL child.

  2. For example:

    For the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7 N

Second line of each test case will contain the integer value k.

The kth largest element for given input tree.

Your Task:
You don't need to read input or print anything. Your task is to complete the function kthLargest() which takes the root of the BST and an integer K as inputs and returns the Kth largest element in the given BST.

Expected Time Complexity: O(H + K).
Expected Auxiliary Space: O(H).

1 <= T <= 1000
1 <= N <= 1000
1 <= K <= N

Example(To be used only for expected output):

4 2 9 1 3 N 10
9 N 10

Note: The Input/Ouput format and Example is given are used for the system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from the stdin/console. The task is to complete the function specified, and not to write the full code.

** For More Input/Output Examples Use 'Expected Output' option **

Contributor: Saksham Raj Seth
Author: saksham seth

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.

Need help with your code? Please use ide.geeksforgeeks.org, generate link and share the link here.

to report an issue on this page.