Saturday, January 30, 2016

Kth largest number in BST

Question: Given a Binary Search Tree (BST) and a positive integer k, find the k’th largest element in the Binary Search Tree.
For example, in the following BST, if k = 3, then output should be 14, and if k = 5, then output should be 10.

Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Public void kthLargest(TreeNode T, int k, int count) {
if(T=!NULL) {
kthLargest(T.right, k, count);
count++;
if(count == k) {
System.out.println(T.element);
return;
}
kthLargest(T.left, k, count);
}
}

No comments:

Post a Comment