I'm trying to implement TreeMap class, and I'm having a problem while putting elements in the TreeMap. Here's the code:
public class TreeMap<K,V> implements Map<K,V> {
private Comparator<K> comparator;
private int size;
private Node<K,V> head;
public TreeMap(Comparator<K> comparator){
this.comparator = comparator;
size = 0;
}
@Override
public int size() {
return size;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public V put(K key, V value) {
return rootPut(head, key, value);
}
private V rootPut(Node<K,V> node, K key, V value){
if(isEmpty()){
node = new Node<>(key, value);
size++;
return null;
}
int compare = comparator.compare(head.key, key);
if(compare == 0){
V auxValue = node.value;
node.value = value;
size++;
return auxValue;
} else if(compare > 0){
return rootPut(node.right, key, value);
} else{
return rootPut(node.left, key, value);
}
}
}
The problem is that when I execute this line:
node = new Node<>(key, value);
node is always null. I've already tried debugging the code, but the problem persists.
The other methods I didn't include here because they work.