Kth Largest in BST
https://workat.tech/problem-solving/practice/kth-largest-element-bst
Given the root node of a binary search tree and a number k
, find out the kth largest element (1-indexed) in the BST.
Note: You can assume that k <= number of nodes.
Testing
Input Format
The first line contains an integer T denoting the number of test cases.
For each test case, the input has 2 lines:
- The first line contains an integer n denoting the number of nodes in the tree (including the NULL nodes).
- The second line contains n space-separated integers that will form the binary tree. The integers follow level order traversal of the tree where -1 indicates a NULL node.
- The third line contains an integer k.
Output Format
For each test case, the output contains an integer with the value of the kth largest element in BST.
Sample Input
4
9
2 1 3 -1 -1 -1 5 4 7
4
7
6 3 21 -1 -1 -1 89
1
12
8 3 9 -1 4 -1 10 -1 -1 -1 12 11
7
4
28 14 -1 11
2
Expected Output
3
89
3
14
1 <= T <= 10
1 <= n <= 105
1 <= node value <= 109
---
Related problems
----
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
/* This is the Node class definition | |
class Node { | |
public Node left; | |
public Node right; | |
public int data; | |
public Node(int data) { | |
this.data = data; | |
} | |
} | |
*/ | |
int findKthLargest(Node root, int k) { | |
Stack<Node> stack = new Stack<Node>(); | |
stack.push(root); | |
while (!stack.isEmpty()) { | |
while (root != null) { | |
stack.push(root); | |
root = root.right; | |
} | |
root = stack.pop(); | |
k -=1; | |
if (k == 0) { | |
return root.data; | |
} | |
root = root.left; | |
} | |
return -1; | |
} | |
} |