-
Notifications
You must be signed in to change notification settings - Fork 0
/
KthLargestNumberInBST
46 lines (32 loc) · 969 Bytes
/
KthLargestNumberInBST
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*************************************************************
Following is the Binary Search Tree node structure
class TreeNode<T> {
public T data;
public TreeNode<T> left;
public TreeNode<T> right;
TreeNode(T data) {
this.data = data;
left = null;
right = null;
}
}
*************************************************************/
import java.util.ArrayList;
public class Solution {
public static int KthLargestNumber(TreeNode<Integer> root, int k) {
ArrayList<Integer> list = new ArrayList<>();
inOrder(list,root);
int size = list.size();
if(size<k)
return -1;
return list.get(size-k);
}
public static void inOrder(ArrayList<Integer> list,TreeNode<Integer> root){
if(root==null)
return;
inOrder(list,root.left);
list.add(root.data);
inOrder(list,root.right);
return ;
}
}