Skip to content

Instantly share code, notes, and snippets.

@linnykoleh
Created May 3, 2017 13:22
Show Gist options
  • Save linnykoleh/2a96dd3218f059d526a0216d0cc7b0de to your computer and use it in GitHub Desktop.
Save linnykoleh/2a96dd3218f059d526a0216d0cc7b0de to your computer and use it in GitHub Desktop.
public V put(K key, V value) {
Entry<K, V> entry = this.root;
if (entry == null) {
this.root = new Entry<>(key, value, null);
return null;
}
int cmp;
Entry<K, V> parent;
Comparator<? super K> cpr = comparator;
if (cpr != null) {
do {
parent = entry;
cmp = cpr.compare(key, entry.key);
if (cmp < 0) {
entry = entry.left;
} else if (cmp > 0) {
entry = entry.right;
} else {
return entry.setValue(value);
}
} while (entry != null);
} else {
if (key == null) throw new NullPointerException();
Comparable<? super K> keyOfInsertValue = (Comparable<? super K>) key;
do {
parent = entry;
cmp = keyOfInsertValue.compareTo(entry.key);
if (cmp < 0) {
entry = entry.left;
} else if (cmp > 0) {
entry = entry.right;
} else {
return entry.setValue(value);
}
} while (entry != null);
}
Entry<K, V> entryOfKey = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = entryOfKey;
else
parent.right = entryOfKey;
elements++;
fixAfterInsertion(entryOfKey);
return null;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment