Last active
September 14, 2022 03:32
-
-
Save 1gravity/4cb46732fde1dbef409baa1700ef20e0 to your computer and use it in GitHub Desktop.
Kotlin Trie Delete Basic
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
override fun delete(key: String) { | |
delete(key, 0, root) | |
} | |
private fun delete(key: String, index: Int, node: Node<Value>): Trie.Node<Value>? { | |
if (index == key.length) { | |
node.value = null | |
if (node.children.isEmpty()) return null | |
return node | |
} | |
val child = node.children[key[index]] ?: return null | |
val deleteChild = delete(key, index + 1, child) == null | |
if (deleteChild) { | |
node.children.remove(key[index]) | |
if (node.children.isEmpty() && node.value == null) return null | |
} | |
return node | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment