From 137dabe066cae885427555b5a87cda7f69eb75fa Mon Sep 17 00:00:00 2001 From: huangsimin Date: Wed, 13 Mar 2019 14:34:20 +0800 Subject: [PATCH] =?UTF-8?q?TODO:=20=E4=BF=AE=E6=94=B9=E5=90=8E=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E4=B8=8D=E6=AD=A3=E7=A1=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- avl/iterator.go | 61 +++++++++++++++++++------------------------------ 1 file changed, 24 insertions(+), 37 deletions(-) diff --git a/avl/iterator.go b/avl/iterator.go index 1ca8d57..a14347c 100644 --- a/avl/iterator.go +++ b/avl/iterator.go @@ -31,17 +31,7 @@ func (iter *Iterator) Next() (result bool) { if iter.cur != nil { iter.tstack.Clear() iter.curPushNextStack(iter.cur) - - iter.up = iter.cur - for iter.up != nil { - if iter.up.child == 1 { - iter.up = iter.up.parent - break - } else { - iter.up = iter.up.parent - } - } - + iter.up = iter.getNextUp(iter.cur) } } iter.dir = 1 @@ -50,14 +40,7 @@ func (iter *Iterator) Next() (result bool) { if iter.tstack.Size() == 0 { if iter.up != nil { iter.tstack.Push(iter.up) - for iter.up != nil { - if iter.up.child == 1 { - iter.up = iter.up.parent - break - } else { - iter.up = iter.up.parent - } - } + iter.up = iter.getNextUp(iter.cur) } else { return false } @@ -72,6 +55,16 @@ func (iter *Iterator) Next() (result bool) { 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] @@ -84,6 +77,16 @@ func (iter *Iterator) curPushNextStack(cur *Node) { } } +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] @@ -104,16 +107,7 @@ func (iter *Iterator) Prev() (result bool) { if iter.cur != nil { iter.tstack.Clear() iter.curPushPrevStack(iter.cur) - - iter.up = iter.cur - for iter.up != nil { - if iter.up.child == 0 { - iter.up = iter.up.parent - break - } else { - iter.up = iter.up.parent - } - } + iter.up = iter.getPrevUp(iter.cur) } } iter.dir = -1 @@ -122,14 +116,7 @@ func (iter *Iterator) Prev() (result bool) { if iter.tstack.Size() == 0 { if iter.up != nil { iter.tstack.Push(iter.up) - for iter.up != nil { - if iter.up.child == 0 { - iter.up = iter.up.parent - break - } else { - iter.up = iter.up.parent - } - } + iter.up = iter.getPrevUp(iter.cur) } else { return false }