Skip to content

Commit d0a7a6d

Browse files
author
Christian Encarnacion
committed
Update ReadMe.md
1 parent 6dd9002 commit d0a7a6d

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed

Trie/ReadMe.md

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,78 @@ And the corresponding swift code:
123123

124124
```
125125

126+
###Removal
127+
Removing keys from the trie is a little more tricky, as there a few more cases that we have to take into account the fact that keys may exist that are actually sub-strings of other valid keys. That being said, it isn't as simple a process to just delete the nodes for a specific key, as we could be deleting references/nodes necessary for already exisitng keys!
126128

129+
The algorithm would be as follows:
130+
131+
```
132+
133+
let word be the key to remove
134+
let node be the root of the trie
135+
136+
find(word)
137+
if word was not found
138+
return false
139+
else
140+
141+
for each character in word
142+
node = child node with value character
143+
144+
if node has more than just 1 child node
145+
Mark node as an invalid key, since removing it would remove nodes still in use
146+
else
147+
while node has no valid children and node is not the root node
148+
let character = node's value
149+
node = the parent of node
150+
delete node's child node with value character
151+
return true
152+
```
153+
154+
155+
156+
and the corresponding swift code:
157+
158+
```swift
159+
func remove(w: String) -> (word: String, removed: Bool){
160+
let word = w.lowercaseString
161+
162+
if(!self.contains(w)) {
163+
return (w, false)
164+
}
165+
var currentNode = self.root
166+
167+
for c in word.characters {
168+
currentNode = currentNode.getChildAt(String(c))
169+
}
170+
171+
if currentNode.numChildren() > 0 {
172+
currentNode.isNotWord()
173+
} else {
174+
var character = currentNode.char()
175+
while(currentNode.numChildren() == 0 && !currentNode.isRoot()) {
176+
currentNode = currentNode.getParent()
177+
currentNode.children[character]!.setParent(nil)
178+
currentNode.children[character]!.update(nil)
179+
currentNode.children[character] = nil
180+
character = currentNode.char()
181+
}
182+
}
183+
184+
wordCount -= 1
185+
186+
var index = 0
187+
for item in wordList{
188+
if item == w {
189+
wordList.removeAtIndex(index)
190+
}
191+
index += 1
192+
}
193+
194+
return (w, true)
195+
}
196+
197+
```
127198

128199

129200

0 commit comments

Comments
 (0)