Skip to content

Commit

Permalink
forced in-order nodes iteration (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
s0rg authored Mar 19, 2024
1 parent fdd3223 commit de854de
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 7 deletions.
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module github.com/s0rg/trie

go 1.21.0
go 1.22
5 changes: 5 additions & 0 deletions node.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package trie

import "slices"

type node[T any] struct {
childs map[rune]*node[T]
order []rune
parent *node[T]
value T
ok bool
Expand Down Expand Up @@ -37,6 +40,8 @@ func (n *node[T]) AddChild(r rune) (rv *node[T]) {

rv.parent = n
n.childs[r] = rv
n.order = append(n.order, r)
slices.Sort(n.order)

return rv
}
Expand Down
17 changes: 11 additions & 6 deletions trie.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ type Trie[T any] struct {

// New creates empty Trie.
func New[T any]() *Trie[T] {
return &Trie[T]{root: makeNode[T](rootNode)}
return &Trie[T]{
root: makeNode[T](rootNode),
}
}

// Add inserts new key/value pair.
Expand Down Expand Up @@ -61,8 +63,7 @@ func (t *Trie[T]) Del(key string) (ok bool) {
}

for ; n != nil; n = p {
p = n.Parent()
if p == nil {
if p = n.Parent(); p == nil {
break
}

Expand Down Expand Up @@ -142,7 +143,7 @@ func (t *Trie[T]) Common(prefix string, minLength int) (rv []string) {
return true
})

slices.SortStableFunc(rv, func(a, b string) int {
slices.SortFunc(rv, func(a, b string) int {
sa, _ := t.Suggest(a)
sb, _ := t.Suggest(b)

Expand Down Expand Up @@ -193,7 +194,9 @@ func dfsValues[T any](
prefix string,
handler func(key string, value T),
) {
for r, c := range n.childs {
for _, r := range n.order {
c := n.childs[r]

key := prefix + string(r)

if c.HasValue() {
Expand All @@ -209,7 +212,9 @@ func dfsKeys[T any](
prefix string,
handler func(string, *node[T]) bool,
) {
for r, c := range n.childs {
for _, r := range n.order {
c := n.childs[r]

key := prefix + string(r)

if !handler(key, c) {
Expand Down

0 comments on commit de854de

Please sign in to comment.