Skip to content

Commit 864c92d

Browse files
committed
Added python version of trie
1 parent bc91d88 commit 864c92d

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

trie.md

+53
Original file line numberDiff line numberDiff line change
@@ -62,9 +62,62 @@ class Trie {
6262
Node node = search(word);
6363
return node != null && node.isLeaf;
6464
}
65+
6566
boolean startsWith(String word) {
6667
Node node = search(word);
6768
return node != null;
6869
}
6970
}
7071
```
72+
73+
```python
74+
class Node:
75+
def __init__(self, character):
76+
self.character = character
77+
self.children = {}
78+
self.isLeaf = False
79+
80+
def __repr__(self):
81+
return self.character + " -> " + str(self.children)
82+
83+
class Trie:
84+
def __init__(self):
85+
self.root = Node("")
86+
87+
def __str__(self):
88+
return str(self.root)
89+
90+
def insert(self, word):
91+
children = self.root.children
92+
for index, c in enumerate(word):
93+
current = None
94+
if c in children.keys():
95+
current = children[c]
96+
else:
97+
current = Node(c)
98+
children[c] = current
99+
100+
if index == len(word) - 1:
101+
current.isLeaf = True
102+
103+
children = current.children
104+
105+
def search(self, word):
106+
node = self.doSearch(word)
107+
return node is not None and node.isLeaf
108+
109+
def startsWith(self, word):
110+
return self.doSearch(word) is not None
111+
112+
def doSearch(self, word):
113+
children = self.root.children
114+
current = None
115+
for c in word:
116+
if c in children.keys():
117+
current = children[c]
118+
children = current.children
119+
else:
120+
current = None
121+
122+
return current
123+
```

0 commit comments

Comments
 (0)