Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Trie in GOLang #171

Merged
merged 1 commit into from
Oct 1, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions GO/Structure/trie/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package main

import "fmt"

// AlphabetSize is the number of possible characters in the trie
const AlphabetSize = 26

// Node represents each node in the trie
type Node struct {
children [26]*Node
isEnd bool
}

// Trie represenst a trie and has a pointer to the root node
type Trie struct {
root *Node
}

// InitTrie will create new Trie
func InitTrie() *Trie {
result := &Trie{root: &Node{}}
return result
}

// Insert will take in a word and add it to the trie
func (t *Trie) Insert(w string) {
wordLength := len(w)
currentNode := t.root
for i := 0; i < wordLength; i++ {
charIndex := w[i] - 'a'
if currentNode.children[charIndex] == nil {
currentNode.children[charIndex] = &Node{}
}
currentNode = currentNode.children[charIndex]
}
currentNode.isEnd = true
}

// Search will take in a word and RETURN true is that word is included in the trie
func (t *Trie) Search(w string) bool {
wordLength := len(w)
currentNode := t.root
for i := 0; i < wordLength; i++ {
charIndex := w[i] - 'a'
if currentNode.children[charIndex] == nil {
return false
}
currentNode = currentNode.children[charIndex]
}
if currentNode.isEnd == true {
return true
}

return false
}

func main() {
myTrie := InitTrie()

toAdd := []string{
"aragorn",
"aragon",
"argon",
"eragon",
"oregon",
"oregano",
"oreo",
}

for _, v := range toAdd {
myTrie.Insert(v)
}

fmt.Println(myTrie.Search("wizard"))
}