Skip to content

Commit

Permalink
Fix order of elements returned from Ancestors()
Browse files Browse the repository at this point in the history
  • Loading branch information
Daisuke Maki committed Oct 13, 2024
1 parent ac25977 commit 4e0cc01
Showing 1 changed file with 21 additions and 7 deletions.
28 changes: 21 additions & 7 deletions trie.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,10 @@ type Node[K cmp.Ordered, V any] interface {

// New creates a new Trie object.
func New[L any, K cmp.Ordered, V any](tokenizer Tokenizer[L, K]) *Trie[L, K, V] {
node := newNode[K, V]()
node.isRoot = true
return &Trie[L, K, V]{
root: newNode[K, V](),
root: node,
tokenizer: tokenizer,
}
}
Expand Down Expand Up @@ -220,7 +222,7 @@ func put[K cmp.Ordered, V any](root Node[K, V], tokens []K, value V) {
if cur == nil {
newRoot = newNode
} else {
cur.children = append(cur.children, newNode)
cur.AddChild(newNode)
}
cur = newNode
}
Expand All @@ -234,6 +236,7 @@ type node[K cmp.Ordered, V any] struct {
mu sync.RWMutex
key K
value V
isRoot bool
children []*node[K, V]
parent *node[K, V]
}
Expand All @@ -255,13 +258,24 @@ func (n *node[K, V]) Parent() Node[K, V] {
}

func (n *node[K, V]) Ancestors() iter.Seq[Node[K, V]] {
var ancestors []*node[K, V]
for {
n = n.parent
if n == nil {
break
}
ancestors = append(ancestors, n)
}

return func(yield func(Node[K, V]) bool) {
cur := n.parent
for cur != nil {
if !yield(cur) {
break
for len(ancestors) > 0 {
cur := ancestors[len(ancestors)-1]
if cur != nil && !cur.isRoot {
if !yield(cur) {
break
}
}
cur = cur.parent
ancestors = ancestors[:len(ancestors)-1]
}
}
}
Expand Down

0 comments on commit 4e0cc01

Please sign in to comment.