Created
March 3, 2023 21:47
-
-
Save vxcute/99828d47258dc47cdc7ad0d066eca026 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
"log" | |
) | |
const R = 256 | |
type TrieNode[T any] struct { | |
value T | |
children [R]*TrieNode[T] | |
size int | |
end bool | |
} | |
func NewTrieNode[T any]() *TrieNode[T] { | |
return &TrieNode[T]{} | |
} | |
func (t *TrieNode[T]) Set(key string, value T) { | |
cur := t | |
for i := range key { | |
if cur.children[i] == nil { | |
cur.children[i] = NewTrieNode[T]() | |
} | |
cur = cur.children[i] | |
} | |
cur.value = value | |
cur.end = true | |
cur.size++ | |
} | |
func (t *TrieNode[T]) Get(key string, value *T) error { | |
cur := t | |
for i := range key { | |
if cur.children[i] == nil { | |
return errors.New("key not found") | |
} | |
cur = cur.children[i] | |
} | |
if cur.end { | |
*value = cur.value | |
return nil | |
} else { | |
return errors.New("key not found") | |
} | |
} | |
func (t *TrieNode[T]) Size() int { | |
return t.size | |
} | |
func main() { | |
trie := NewTrieNode[int]() | |
trie.Set("Ahmed", 18) | |
var x int | |
err := trie.Get("Ahmed", &x) | |
if err != nil { | |
log.Fatal(err) | |
} | |
println(x) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment