-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.go
52 lines (45 loc) · 1.16 KB
/
trie.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package datastructures
type TrieNode struct {
children [26]*TrieNode
wordEnd bool
}
type Trie struct {
rootNode *TrieNode
}
// Constructor to initialize the Trie
func Constructor() Trie {
return Trie{rootNode: &TrieNode{}}
}
// Insert a word into the Trie
func (t *Trie) Insert(word string) {
// Start from the root node
node := t.rootNode
// Insert each character of the word
for _, char := range word {
index := char - 'a'
// Create a new node if the character is not found
if node.children[index] == nil {
node.children[index] = &TrieNode{}
}
// Move to the next node
node = node.children[index]
}
node.wordEnd = true
}
// Search for a word in the Trie
func (t *Trie) Search(word string) bool {
// Start from the root node
node := t.rootNode
// Traverse the Trie following the characters of the word one by one
for _, char := range word {
index := char - 'a'
// Return false if the character is not found
if node.children[index] == nil {
return false
}
// Otherwise move to the next node in the Trie
node = node.children[index]
}
// If at the end of the word, return true if the node is marked as end of word
return node.wordEnd
}