Please critique my code. (Specifically, I'm not sure if my use of member variables is appropriate.)
Here is the main structure of my BST class:
public class bst {
private Node root;
public class Node {
int data;
Node left, right;
private Node(int data) {
this.data = data;
left = null;
right = null;
}
}
}
The bst class contains the following methods to find kth max/min element
private static int min;
private static int max;
private static int target;
private static boolean isFound;
private static int level;
private static int nodes;
public int KthMin(int k) {
//initializing helper variables
target = k;
isFound = false;
min = 0;
level = 1;
nodes = 0;
KthMinHelper(root);
if (target > nodes) {
throw new IndexOutOfBoundsException();
}
return min;
}
private void KthMinHelper(Node n) {
if (isFound) {
return;
}
nodes++;
if (n.left != null) {
KthMinHelper(n.left);
}
if (level == target) {
min = n.data;
isFound = true;
}
level++;
if (n.right != null) {
KthMinHelper(n.right);
}
}
public int KthMax(int k) {
//initializing helper variables
target = k;
max = 0;
isFound = false;
level = 1;
nodes = 0;
KthMaxHelper(root);
if (target > nodes) {
throw new IndexOutOfBoundsException();
}
return max;
}
private void KthMaxHelper(Node n) {
if (isFound) {
return;
}
nodes++;
if (n.right != null) {
KthMaxHelper(n.right);
}
if (level == target) {
max = n.data;
isFound = true;
}
level++;
if (n.left != null) {
KthMaxHelper(n.left);
}
}
This is how my test driver looks like:
public static void main(String[] args) {
bst tree = new bst();
int[] a = {11, 5, 2, 9, 7, 6, 3};
for (Integer n : a) {
tree.insert(n);
}
System.out.println("\nkth min:" + tree.KthMin(3));
System.out.println("kth max:" + tree.KthMax(2));
}