structure/avl/iterator.go

67 lines
1.1 KiB
Go
Raw Normal View History

2019-03-12 11:18:42 +00:00
package avl
import (
"log"
"github.com/emirpasic/gods/stacks/arraystack"
)
type Iterator struct {
op *AVL
cur *Node
prevstack *arraystack.Stack
nextstack *arraystack.Stack
// curnext *Node
}
func initIterator(avltree *AVL) *Iterator {
iter := &Iterator{op: avltree, prevstack: arraystack.New(), nextstack: arraystack.New()}
iter.cur = avltree.root
// iter.nextstack.Push(avltree.root)
return iter
}
func (iter *Iterator) Value() interface{} {
return iter.cur.value
}
func (iter *Iterator) Next() (result bool) {
if iter.nextstack.Size() == 0 {
iter.nextstack.Push(iter.cur)
}
if v, ok := iter.nextstack.Pop(); ok {
iter.cur = v.(*Node)
iter.curPushNextStack(iter.cur)
log.Println(iter.nextstack.Size())
return true
}
return false
}
func (iter *Iterator) curPushNextStack(cur *Node) {
next := cur.children[0]
if next != nil {
iter.nextstack.Push(next)
for next.children[1] != nil {
next = next.children[1]
iter.nextstack.Push(next)
}
}
}
func (iter *Iterator) Prev() (result bool) {
if v, ok := iter.nextstack.Pop(); ok {
iter.cur = v.(*Node)
iter.curPushNextStack(iter.cur)
return true
}
return false
}