Skip to content

Commit 6473e47

Browse files
authored
Create Trie.md
1 parent a5fcdb0 commit 6473e47

File tree

1 file changed

+45
-0
lines changed
  • docs/Leetcode_Solutions/Python/Summary/Tree

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
```python
2+
class TrieNode(object):
3+
4+
def __init__(self):
5+
self.children = dict()
6+
self.isWordEnd = False
7+
8+
def buildTrie(self, words):
9+
for word in words:
10+
curr = self
11+
for char in word:
12+
if char not in curr.children:
13+
curr.children[char] = TrieNode()
14+
curr = curr.children[char]
15+
curr.isWordEnd = True
16+
17+
def find(self, word):
18+
curr = self
19+
for char in word:
20+
if char not in curr.children:
21+
return False
22+
curr = curr.children[char]
23+
return curr.isWordEnd
24+
25+
def print_words(node, word):
26+
27+
if node.isWordEnd:
28+
print(word, end=' ')
29+
30+
for key, value in node.children.items():
31+
print_words(value, word + key)
32+
33+
34+
def test():
35+
words = ['banana', 'bananas', 'bandana', 'band', 'apple', 'all', 'beast']
36+
root = TrieNode()
37+
root.buildTrie(words)
38+
print_words(root, '')
39+
assert root.find('banana')
40+
assert not root.find('bandanas')
41+
assert not root.find('apps')
42+
assert root.find('apple')
43+
44+
test()
45+
```

0 commit comments

Comments
 (0)