Hi I have a programming project where I'm basically using a Binary Search Tree to implement a min/max priority queue. I'm having trouble with the popMin/popMax methods. I get how to get the minimum/maximum node and remove a node, but I'm having trouble doing both with a single recursive method.
I don't understand how I can return null value to assign to the parent node's left value, and also return the minimum value to the original method caller.
Right now I'm just using a class variable min to record the minimum, but I'm not sure if that's absolutely necessary. My node class is not allowed a parent data member.
Here is my code:
private int min;
public int removeMin() {
if (root == null) { //if Queue is empty
System.out.println("Queue is empty");
return 0;
}
root = removeMin(root);
return min;
}
private Node removeMin(Node n){
if (n.left == null) {
min = n.key;
if (n.right != null){ //if a right child exists
size--;
return n.right;
}
else {
size--;
n = null;
return n;
}
} else {
n.left = removeMin(n.left);
return n;
}
}