https://github.com/beevik/prefixtree
A prefix tree (trie) implementation in go
https://github.com/beevik/prefixtree
data-structures prefix prefix-tree prefix-trie trie
Last synced: 5 months ago
JSON representation
A prefix tree (trie) implementation in go
- Host: GitHub
- URL: https://github.com/beevik/prefixtree
- Owner: beevik
- License: bsd-2-clause
- Created: 2015-02-09T20:42:57.000Z (over 10 years ago)
- Default Branch: v2
- Last Pushed: 2024-07-13T03:03:35.000Z (10 months ago)
- Last Synced: 2024-11-25T15:54:01.721Z (6 months ago)
- Topics: data-structures, prefix, prefix-tree, prefix-trie, trie
- Language: Go
- Homepage:
- Size: 68.4 KB
- Stars: 34
- Watchers: 4
- Forks: 8
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://godoc.org/github.com/beevik/prefixtree/v2)
[](https://github.com/beevik/prefixtree/actions/workflows/go.yml)prefixtree
==========The prefixtree package implements a simple prefix trie data structure.
The tree enables rapid searching for strings that uniquely match a given
prefix. The implementation allows the user to associate data with each
string, so it can act as a sort of flexible key-value store where
searches succeed with the shortest unambiguous key prefix.This is version 2 of the package, which you can retrieve using `go get`:
```sh
go get github.com/beevik/prefixtree/v2
```### Example: Building a prefix tree
The following code adds strings and associated data (in this case an integer)
to a prefix tree.```go
tree := prefixtree.New[int]()tree.Add("apple", 10)
tree.Add("orange", 20)
tree.Add("apple pie", 30)
tree.Add("lemon", 40)
tree.Add("lemon meringue pie", 50)
```### Example: Searching the prefix tree
The following code searches the prefix tree generated by the
previous example and outputs the results.```go
fmt.Printf("%-18s %-8s %s\n", "prefix", "value", "error")
fmt.Printf("%-18s %-8s %s\n", "------", "-----", "-----")for _, prefix := range []string{
"a",
"appl",
"apple",
"apple p",
"apple pie",
"apple pies",
"o",
"oran",
"orange",
"oranges",
"l",
"lemo",
"lemon",
"lemon m",
"lemon meringue",
"pear",
} {
value, err := tree.FindValue(prefix)
fmt.Printf("%-18s %-8v %v\n", prefix, value, err)
}
```Output:
```
prefix value error
------ ----- -----
a 0 prefixtree: prefix ambiguous
appl 0 prefixtree: prefix ambiguous
apple 10
apple p 30
apple pie 30
apple pies 0 prefixtree: prefix not found
o 20
oran 20
orange 20
oranges 0 prefixtree: prefix not found
l 0 prefixtree: prefix ambiguous
lemo 0 prefixtree: prefix ambiguous
lemon 40
lemon m 50
lemon meringue 50
pear 0 prefixtree: prefix not found
```