Skip to content

Instantly share code, notes, and snippets.

@1gravity
Created September 14, 2022 16:34
Show Gist options
  • Save 1gravity/75f836077eb23f4d892585bbc372a5d1 to your computer and use it in GitHub Desktop.
Save 1gravity/75f836077eb23f4d892585bbc372a5d1 to your computer and use it in GitHub Desktop.
Kotlin Trie Non-Recursive Delete
override fun delete(key: String) {
// search leaf
key.fold(root) { node, char ->
node.children[char] ?: return
}.let { leaf ->
leaf.value = null
key.foldRight(leaf) { char, current ->
if (current.children.isEmpty() && current.value == null) {
current.parent?.apply { children.remove(char) } ?: return
} else return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment