Created
May 3, 2017 13:22
-
-
Save linnykoleh/2a96dd3218f059d526a0216d0cc7b0de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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