133 lines
2.3 KiB
Go
133 lines
2.3 KiB
Go
package avl
|
|
|
|
import (
|
|
"474420502.top/eson/structure/lastack"
|
|
)
|
|
|
|
type Iterator struct {
|
|
op *AVL
|
|
|
|
dir int
|
|
up *Node
|
|
cur *Node
|
|
tstack *lastack.Stack
|
|
// curnext *Node
|
|
}
|
|
|
|
func initIterator(avltree *AVL) *Iterator {
|
|
iter := &Iterator{op: avltree, tstack: lastack.New()}
|
|
iter.up = avltree.root
|
|
return iter
|
|
}
|
|
|
|
func (iter *Iterator) Value() interface{} {
|
|
return iter.cur.value
|
|
}
|
|
|
|
func (iter *Iterator) Next() (result bool) {
|
|
|
|
if iter.dir < 1 {
|
|
if iter.dir == -1 {
|
|
if iter.cur != nil {
|
|
iter.tstack.Clear()
|
|
iter.curPushNextStack(iter.cur)
|
|
iter.up = iter.getNextUp(iter.cur)
|
|
}
|
|
}
|
|
iter.dir = 1
|
|
}
|
|
|
|
if iter.tstack.Size() == 0 {
|
|
if iter.up != nil {
|
|
iter.tstack.Push(iter.up)
|
|
iter.up = iter.getNextUp(iter.cur)
|
|
} else {
|
|
return false
|
|
}
|
|
}
|
|
|
|
if v, ok := iter.tstack.Pop(); ok {
|
|
iter.cur = v.(*Node)
|
|
iter.curPushNextStack(iter.cur)
|
|
return true
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
func (iter *Iterator) getNextUp(cur *Node) *Node {
|
|
for cur != nil {
|
|
if cur.child == 1 { // next 在 降序 小值. 如果child在右边, parent 比 child 小, parent才有效, 符合降序
|
|
return cur.parent
|
|
}
|
|
cur = cur.parent
|
|
}
|
|
return cur
|
|
}
|
|
|
|
func (iter *Iterator) curPushNextStack(cur *Node) {
|
|
next := cur.children[0]
|
|
|
|
if next != nil {
|
|
iter.tstack.Push(next)
|
|
for next.children[1] != nil {
|
|
next = next.children[1]
|
|
iter.tstack.Push(next)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (iter *Iterator) getPrevUp(cur *Node) *Node {
|
|
for cur != nil {
|
|
if cur.child == 0 { // Prev 在 降序 大值. 如果child在左边, parent 比 child 大, parent才有效 , 符合降序
|
|
return cur.parent
|
|
}
|
|
cur = cur.parent
|
|
}
|
|
return cur
|
|
}
|
|
|
|
func (iter *Iterator) curPushPrevStack(cur *Node) {
|
|
prev := cur.children[1]
|
|
|
|
if prev != nil {
|
|
iter.tstack.Push(prev)
|
|
for prev.children[0] != nil {
|
|
prev = prev.children[0]
|
|
iter.tstack.Push(prev)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (iter *Iterator) Prev() (result bool) {
|
|
|
|
if iter.dir > -1 {
|
|
|
|
if iter.dir == 1 {
|
|
if iter.cur != nil {
|
|
iter.tstack.Clear()
|
|
iter.curPushPrevStack(iter.cur)
|
|
iter.up = iter.getPrevUp(iter.cur)
|
|
}
|
|
}
|
|
iter.dir = -1
|
|
}
|
|
|
|
if iter.tstack.Size() == 0 {
|
|
if iter.up != nil {
|
|
iter.tstack.Push(iter.up)
|
|
iter.up = iter.getPrevUp(iter.cur)
|
|
} else {
|
|
return false
|
|
}
|
|
}
|
|
|
|
if v, ok := iter.tstack.Pop(); ok {
|
|
iter.cur = v.(*Node)
|
|
iter.curPushPrevStack(iter.cur)
|
|
return true
|
|
}
|
|
|
|
return false
|
|
}
|