new file: .gitignore
new file: LICENSE new file: README.md new file: compare/compare.go new file: for_test.go new file: heap/heap.go new file: heap/heap_test.go new file: interface.go new file: lastack/lastack.go new file: lastack/lastack_test.go new file: list/list.go new file: list/list_test.go new file: map/hashmap/hashmap.go new file: map/hashmap/hashmap_test.go new file: priority_list/iterator.go new file: priority_list/priority_list.go new file: priority_list/priority_list_test.go new file: priority_queue/iterator.go new file: priority_queue/priority_queue.go new file: priority_queue/priority_queue_test.go new file: priority_queue/vbt.go new file: priority_queue/vbt_test.go new file: priority_queuekey/iterator.go new file: priority_queuekey/priority_queuekey.go new file: priority_queuekey/priority_queuekey_test.go new file: priority_queuekey/vbt.go new file: priority_queuekey/vbt_test.go new file: set/hashset/hashset.go new file: set/hashset/hashset_test.go new file: set/treeset/treeset.go new file: set/treeset/treeset_test.go new file: sparse_array/array2/array2.go new file: sparse_array/array2/array2_test.go new file: sparse_array/array3/array3.go new file: sparse_array/array3/array3_test.go new file: sparse_array/arrayn/arrayn.go new file: sparse_array/arrayn/arrayn_test.go new file: stack/stack.go new file: stack/stack_test.go new file: tree/avl/avl.go new file: tree/avl/avl_test.go new file: tree/avl/iterator.go new file: tree/avldup/avldup.go new file: tree/avldup/avldup_test.go new file: tree/avldup/iterator.go new file: tree/avlkey/avlkey.go new file: tree/avlkey/avlkey_test.go new file: tree/avlkey/iterator.go new file: tree/avlkeydup/avlkeydup.go new file: tree/avlkeydup/avlkeydup_test.go new file: tree/avlkeydup/iterator.go new file: tree/vbt/iterator.go new file: tree/vbt/vbt.go new file: tree/vbt/vbt_test.go new file: tree/vbtkey/iterator.go new file: tree/vbtkey/vbtkey.go new file: tree/vbtkey/vbtkey_test.go
This commit is contained in:
829
tree/avlkey/avlkey.go
Normal file
829
tree/avlkey/avlkey.go
Normal file
@@ -0,0 +1,829 @@
|
||||
package avlkey
|
||||
|
||||
import (
|
||||
"474420502.top/eson/structure/compare"
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
)
|
||||
|
||||
type Node struct {
|
||||
children [2]*Node
|
||||
parent *Node
|
||||
height int
|
||||
key, value interface{}
|
||||
}
|
||||
|
||||
func (n *Node) String() string {
|
||||
if n == nil {
|
||||
return "nil"
|
||||
}
|
||||
|
||||
p := "nil"
|
||||
if n.parent != nil {
|
||||
p = spew.Sprint(n.parent.value)
|
||||
}
|
||||
return spew.Sprint(n.value) + "(" + p + "|" + spew.Sprint(n.height) + ")"
|
||||
}
|
||||
|
||||
type Tree struct {
|
||||
root *Node
|
||||
size int
|
||||
Compare compare.Compare
|
||||
iter *Iterator
|
||||
}
|
||||
|
||||
func New(Compare compare.Compare) *Tree {
|
||||
return &Tree{Compare: Compare, iter: NewIteratorWithCap(nil, 16)}
|
||||
}
|
||||
|
||||
func (tree *Tree) String() string {
|
||||
if tree.size == 0 {
|
||||
return ""
|
||||
}
|
||||
str := "AVLTree\n"
|
||||
output(tree.root, "", true, &str)
|
||||
|
||||
return str
|
||||
}
|
||||
|
||||
func (tree *Tree) Iterator() *Iterator {
|
||||
return initIterator(tree)
|
||||
}
|
||||
|
||||
func (tree *Tree) Size() int {
|
||||
return tree.size
|
||||
}
|
||||
|
||||
func (tree *Tree) Remove(key interface{}) (interface{}, bool) {
|
||||
|
||||
if n, ok := tree.GetNode(key); ok {
|
||||
|
||||
tree.size--
|
||||
if tree.size == 0 {
|
||||
tree.root = nil
|
||||
return n.value, true
|
||||
}
|
||||
|
||||
left := getHeight(n.children[0])
|
||||
right := getHeight(n.children[1])
|
||||
|
||||
if left == -1 && right == -1 {
|
||||
p := n.parent
|
||||
p.children[getRelationship(n)] = nil
|
||||
tree.fixRemoveHeight(p)
|
||||
return n.value, true
|
||||
}
|
||||
|
||||
var cur *Node
|
||||
if left > right {
|
||||
cur = n.children[0]
|
||||
for cur.children[1] != nil {
|
||||
cur = cur.children[1]
|
||||
}
|
||||
|
||||
cleft := cur.children[0]
|
||||
cur.parent.children[getRelationship(cur)] = cleft
|
||||
if cleft != nil {
|
||||
cleft.parent = cur.parent
|
||||
}
|
||||
|
||||
} else {
|
||||
cur = n.children[1]
|
||||
for cur.children[0] != nil {
|
||||
cur = cur.children[0]
|
||||
}
|
||||
|
||||
cright := cur.children[1]
|
||||
cur.parent.children[getRelationship(cur)] = cright
|
||||
|
||||
if cright != nil {
|
||||
cright.parent = cur.parent
|
||||
}
|
||||
}
|
||||
|
||||
cparent := cur.parent
|
||||
// 修改为interface 交换
|
||||
n.value, cur.value = cur.value, n.value
|
||||
n.key, cur.key = cur.key, n.key
|
||||
|
||||
// 考虑到刚好替换的节点是 被替换节点的孩子节点的时候, 从自身修复高度
|
||||
if cparent == n {
|
||||
tree.fixRemoveHeight(n)
|
||||
} else {
|
||||
tree.fixRemoveHeight(cparent)
|
||||
}
|
||||
|
||||
return cur.value, true
|
||||
}
|
||||
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func (tree *Tree) Clear() {
|
||||
tree.size = 0
|
||||
tree.root = nil
|
||||
tree.iter = NewIteratorWithCap(nil, 16)
|
||||
}
|
||||
|
||||
// Values 返回先序遍历的值
|
||||
func (tree *Tree) Values() []interface{} {
|
||||
mszie := 0
|
||||
if tree.root != nil {
|
||||
mszie = tree.size
|
||||
}
|
||||
result := make([]interface{}, 0, mszie)
|
||||
tree.Traversal(func(k, v interface{}) bool {
|
||||
result = append(result, v)
|
||||
return true
|
||||
}, LDR)
|
||||
return result
|
||||
}
|
||||
|
||||
func (tree *Tree) GetRange(k1, k2 interface{}) (result []interface{}) {
|
||||
c := tree.Compare(k2, k1)
|
||||
switch c {
|
||||
case 1:
|
||||
|
||||
var min, max *Node
|
||||
resultmin := tree.getArountNode(k1)
|
||||
resultmax := tree.getArountNode(k2)
|
||||
for i := 1; i < 3 && min == nil; i++ {
|
||||
min = resultmin[i]
|
||||
}
|
||||
|
||||
for i := 1; i > -1 && max == nil; i-- {
|
||||
max = resultmax[i]
|
||||
}
|
||||
|
||||
if max == nil {
|
||||
return []interface{}{}
|
||||
}
|
||||
|
||||
result = make([]interface{}, 0, 16)
|
||||
|
||||
tree.iter.SetNode(min)
|
||||
iter := tree.iter
|
||||
for iter.Next() {
|
||||
result = append(result, iter.Value())
|
||||
if iter.cur == max {
|
||||
break
|
||||
}
|
||||
}
|
||||
case -1:
|
||||
|
||||
var min, max *Node
|
||||
resultmin := tree.getArountNode(k2)
|
||||
resultmax := tree.getArountNode(k1)
|
||||
for i := 1; i < 3 && min == nil; i++ {
|
||||
min = resultmin[i]
|
||||
}
|
||||
for i := 1; i > -1 && max == nil; i-- {
|
||||
max = resultmax[i]
|
||||
}
|
||||
|
||||
if min == nil {
|
||||
return []interface{}{}
|
||||
}
|
||||
|
||||
result = make([]interface{}, 0, 16)
|
||||
|
||||
tree.iter.SetNode(max)
|
||||
iter := tree.iter
|
||||
for iter.Prev() {
|
||||
result = append(result, iter.Value())
|
||||
if iter.cur == min {
|
||||
break
|
||||
}
|
||||
}
|
||||
case 0:
|
||||
if n, ok := tree.GetNode(k1); ok {
|
||||
return []interface{}{n.value}
|
||||
}
|
||||
return []interface{}{}
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (tree *Tree) Get(key interface{}) (interface{}, bool) {
|
||||
n, ok := tree.GetNode(key)
|
||||
if ok {
|
||||
return n.value, true
|
||||
}
|
||||
return n, false
|
||||
}
|
||||
|
||||
func (tree *Tree) GetAround(key interface{}) (result [3]interface{}) {
|
||||
an := tree.getArountNode(key)
|
||||
for i, n := range an {
|
||||
if n != nil {
|
||||
result[i] = n.value
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (tree *Tree) getArountNode(key interface{}) (result [3]*Node) {
|
||||
var last *Node
|
||||
var lastc int
|
||||
|
||||
for n := tree.root; n != nil; {
|
||||
last = n
|
||||
c := tree.Compare(key, n.key)
|
||||
switch c {
|
||||
case -1:
|
||||
n = n.children[0]
|
||||
lastc = c
|
||||
case 1:
|
||||
n = n.children[1]
|
||||
lastc = c
|
||||
case 0:
|
||||
|
||||
tree.iter.SetNode(n)
|
||||
iter := tree.iter
|
||||
iter.Prev()
|
||||
for iter.Prev() {
|
||||
if tree.Compare(iter.cur.key, n.key) == 0 {
|
||||
n = iter.cur
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
result[1] = n
|
||||
n = nil
|
||||
default:
|
||||
panic("Get Compare only is allowed in -1, 0, 1")
|
||||
}
|
||||
}
|
||||
|
||||
switch lastc {
|
||||
case 1:
|
||||
|
||||
if result[1] != nil {
|
||||
|
||||
result[0] = tree.iter.GetPrev(result[1], 1)
|
||||
result[2] = tree.iter.GetNext(result[1], 1)
|
||||
} else {
|
||||
result[0] = last
|
||||
result[2] = tree.iter.GetNext(last, 1)
|
||||
}
|
||||
|
||||
case -1:
|
||||
|
||||
if result[1] != nil {
|
||||
result[0] = tree.iter.GetPrev(result[1], 1)
|
||||
result[2] = tree.iter.GetNext(result[1], 1)
|
||||
} else {
|
||||
result[2] = last
|
||||
result[0] = tree.iter.GetPrev(last, 1)
|
||||
}
|
||||
|
||||
case 0:
|
||||
|
||||
if result[1] == nil {
|
||||
return
|
||||
}
|
||||
result[0] = tree.iter.GetPrev(result[1], 1)
|
||||
result[2] = tree.iter.GetNext(result[1], 1)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (tree *Tree) GetNode(key interface{}) (*Node, bool) {
|
||||
|
||||
for n := tree.root; n != nil; {
|
||||
switch c := tree.Compare(key, n.key); c {
|
||||
case -1:
|
||||
n = n.children[0]
|
||||
case 1:
|
||||
n = n.children[1]
|
||||
case 0:
|
||||
|
||||
tree.iter.SetNode(n)
|
||||
iter := tree.iter
|
||||
iter.Prev()
|
||||
for iter.Prev() {
|
||||
if tree.Compare(iter.cur.key, n.key) == 0 {
|
||||
n = iter.cur
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
return n, true
|
||||
default:
|
||||
panic("Get Compare only is allowed in -1, 0, 1")
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func (tree *Tree) Put(key, value interface{}) {
|
||||
tree.size++
|
||||
node := &Node{key: key, value: value}
|
||||
if tree.size == 1 {
|
||||
tree.root = node
|
||||
return
|
||||
}
|
||||
|
||||
for cur, c := tree.root, 0; ; {
|
||||
c = tree.Compare(key, cur.key)
|
||||
if c == -1 {
|
||||
if cur.children[0] == nil {
|
||||
cur.children[0] = node
|
||||
cur.children[0].parent = cur
|
||||
if cur.height == 0 {
|
||||
tree.fixPutHeight(cur)
|
||||
}
|
||||
return
|
||||
}
|
||||
cur = cur.children[0]
|
||||
} else {
|
||||
if cur.children[1] == nil {
|
||||
cur.children[1] = node
|
||||
cur.children[1].parent = cur
|
||||
if cur.height == 0 {
|
||||
tree.fixPutHeight(cur)
|
||||
}
|
||||
return
|
||||
}
|
||||
cur = cur.children[1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type TraversalMethod int
|
||||
|
||||
const (
|
||||
// L = left R = right D = Value(dest)
|
||||
_ TraversalMethod = iota
|
||||
//DLR 先值 然后左递归 右递归 下面同理
|
||||
DLR
|
||||
//LDR 先从左边有序访问到右边 从小到大
|
||||
LDR
|
||||
// LRD 同理
|
||||
LRD
|
||||
// DRL 同理
|
||||
DRL
|
||||
// RDL 先从右边有序访问到左边 从大到小
|
||||
RDL
|
||||
// RLD 同理
|
||||
RLD
|
||||
)
|
||||
|
||||
// Traversal 遍历的方法 默认是LDR 从小到大 Compare 为 l < r
|
||||
func (tree *Tree) Traversal(every func(k, v interface{}) bool, traversalMethod ...interface{}) {
|
||||
if tree.root == nil {
|
||||
return
|
||||
}
|
||||
|
||||
method := LDR
|
||||
if len(traversalMethod) != 0 {
|
||||
method = traversalMethod[0].(TraversalMethod)
|
||||
}
|
||||
|
||||
switch method {
|
||||
case DLR:
|
||||
var traverasl func(cur *Node) bool
|
||||
traverasl = func(cur *Node) bool {
|
||||
if cur == nil {
|
||||
return true
|
||||
}
|
||||
if !every(cur.key, cur.value) {
|
||||
return false
|
||||
}
|
||||
if !traverasl(cur.children[0]) {
|
||||
return false
|
||||
}
|
||||
if !traverasl(cur.children[1]) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
traverasl(tree.root)
|
||||
case LDR:
|
||||
var traverasl func(cur *Node) bool
|
||||
traverasl = func(cur *Node) bool {
|
||||
if cur == nil {
|
||||
return true
|
||||
}
|
||||
if !traverasl(cur.children[0]) {
|
||||
return false
|
||||
}
|
||||
if !every(cur.key, cur.value) {
|
||||
return false
|
||||
}
|
||||
if !traverasl(cur.children[1]) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
traverasl(tree.root)
|
||||
case LRD:
|
||||
var traverasl func(cur *Node) bool
|
||||
traverasl = func(cur *Node) bool {
|
||||
if cur == nil {
|
||||
return true
|
||||
}
|
||||
if !traverasl(cur.children[0]) {
|
||||
return false
|
||||
}
|
||||
if !traverasl(cur.children[1]) {
|
||||
return false
|
||||
}
|
||||
if !every(cur.key, cur.value) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
traverasl(tree.root)
|
||||
case DRL:
|
||||
var traverasl func(cur *Node) bool
|
||||
traverasl = func(cur *Node) bool {
|
||||
if cur == nil {
|
||||
return true
|
||||
}
|
||||
if !every(cur.key, cur.value) {
|
||||
return false
|
||||
}
|
||||
if !traverasl(cur.children[0]) {
|
||||
return false
|
||||
}
|
||||
if !traverasl(cur.children[1]) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
traverasl(tree.root)
|
||||
case RDL:
|
||||
var traverasl func(cur *Node) bool
|
||||
traverasl = func(cur *Node) bool {
|
||||
if cur == nil {
|
||||
return true
|
||||
}
|
||||
if !traverasl(cur.children[1]) {
|
||||
return false
|
||||
}
|
||||
if !every(cur.key, cur.value) {
|
||||
return false
|
||||
}
|
||||
if !traverasl(cur.children[0]) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
traverasl(tree.root)
|
||||
case RLD:
|
||||
var traverasl func(cur *Node) bool
|
||||
traverasl = func(cur *Node) bool {
|
||||
if cur == nil {
|
||||
return true
|
||||
}
|
||||
if !traverasl(cur.children[1]) {
|
||||
return false
|
||||
}
|
||||
if !traverasl(cur.children[0]) {
|
||||
return false
|
||||
}
|
||||
if !every(cur.key, cur.value) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
traverasl(tree.root)
|
||||
}
|
||||
}
|
||||
|
||||
func (tree *Tree) lrrotate(cur *Node) {
|
||||
|
||||
const l = 1
|
||||
const r = 0
|
||||
|
||||
movparent := cur.children[l]
|
||||
mov := movparent.children[r]
|
||||
|
||||
mov.value, cur.value = cur.value, mov.value //交换值达到, 相对位移
|
||||
mov.key, cur.key = cur.key, mov.key
|
||||
|
||||
if mov.children[l] != nil {
|
||||
movparent.children[r] = mov.children[l]
|
||||
movparent.children[r].parent = movparent
|
||||
//movparent.children[r].child = l
|
||||
} else {
|
||||
movparent.children[r] = nil
|
||||
}
|
||||
|
||||
if mov.children[r] != nil {
|
||||
mov.children[l] = mov.children[r]
|
||||
//mov.children[l].child = l
|
||||
} else {
|
||||
mov.children[l] = nil
|
||||
}
|
||||
|
||||
if cur.children[r] != nil {
|
||||
mov.children[r] = cur.children[r]
|
||||
mov.children[r].parent = mov
|
||||
} else {
|
||||
mov.children[r] = nil
|
||||
}
|
||||
|
||||
cur.children[r] = mov
|
||||
mov.parent = cur
|
||||
|
||||
mov.height = getMaxChildrenHeight(mov) + 1
|
||||
movparent.height = getMaxChildrenHeight(movparent) + 1
|
||||
cur.height = getMaxChildrenHeight(cur) + 1
|
||||
}
|
||||
|
||||
func (tree *Tree) rlrotate(cur *Node) {
|
||||
|
||||
const l = 0
|
||||
const r = 1
|
||||
|
||||
movparent := cur.children[l]
|
||||
mov := movparent.children[r]
|
||||
|
||||
mov.value, cur.value = cur.value, mov.value //交换值达到, 相对位移
|
||||
mov.key, cur.key = cur.key, mov.key
|
||||
|
||||
if mov.children[l] != nil {
|
||||
movparent.children[r] = mov.children[l]
|
||||
movparent.children[r].parent = movparent
|
||||
} else {
|
||||
movparent.children[r] = nil
|
||||
}
|
||||
|
||||
if mov.children[r] != nil {
|
||||
mov.children[l] = mov.children[r]
|
||||
} else {
|
||||
mov.children[l] = nil
|
||||
}
|
||||
|
||||
if cur.children[r] != nil {
|
||||
mov.children[r] = cur.children[r]
|
||||
mov.children[r].parent = mov
|
||||
} else {
|
||||
mov.children[r] = nil
|
||||
}
|
||||
|
||||
cur.children[r] = mov
|
||||
mov.parent = cur
|
||||
|
||||
mov.height = getMaxChildrenHeight(mov) + 1
|
||||
movparent.height = getMaxChildrenHeight(movparent) + 1
|
||||
cur.height = getMaxChildrenHeight(cur) + 1
|
||||
}
|
||||
|
||||
func (tree *Tree) rrotate(cur *Node) {
|
||||
|
||||
const l = 0
|
||||
const r = 1
|
||||
// 1 right 0 left
|
||||
mov := cur.children[l]
|
||||
|
||||
mov.value, cur.value = cur.value, mov.value //交换值达到, 相对位移
|
||||
mov.key, cur.key = cur.key, mov.key
|
||||
|
||||
// mov.children[l]不可能为nil
|
||||
mov.children[l].parent = cur
|
||||
cur.children[l] = mov.children[l]
|
||||
|
||||
// 解决mov节点孩子转移的问题
|
||||
if mov.children[r] != nil {
|
||||
mov.children[l] = mov.children[r]
|
||||
} else {
|
||||
mov.children[l] = nil
|
||||
}
|
||||
|
||||
if cur.children[r] != nil {
|
||||
mov.children[r] = cur.children[r]
|
||||
mov.children[r].parent = mov
|
||||
} else {
|
||||
mov.children[r] = nil
|
||||
}
|
||||
|
||||
// 连接转移后的节点 由于mov只是与cur交换值,parent不变
|
||||
cur.children[r] = mov
|
||||
|
||||
mov.height = getMaxChildrenHeight(mov) + 1
|
||||
cur.height = getMaxChildrenHeight(cur) + 1
|
||||
}
|
||||
|
||||
func (tree *Tree) lrotate(cur *Node) {
|
||||
|
||||
const l = 1
|
||||
const r = 0
|
||||
|
||||
mov := cur.children[l]
|
||||
|
||||
mov.value, cur.value = cur.value, mov.value //交换值达到, 相对位移
|
||||
mov.key, cur.key = cur.key, mov.key
|
||||
|
||||
// 不可能为nil
|
||||
mov.children[l].parent = cur
|
||||
cur.children[l] = mov.children[l]
|
||||
|
||||
if mov.children[r] != nil {
|
||||
mov.children[l] = mov.children[r]
|
||||
} else {
|
||||
mov.children[l] = nil
|
||||
}
|
||||
|
||||
if cur.children[r] != nil {
|
||||
mov.children[r] = cur.children[r]
|
||||
mov.children[r].parent = mov
|
||||
} else {
|
||||
mov.children[r] = nil
|
||||
}
|
||||
|
||||
cur.children[r] = mov
|
||||
|
||||
mov.height = getMaxChildrenHeight(mov) + 1
|
||||
cur.height = getMaxChildrenHeight(cur) + 1
|
||||
}
|
||||
|
||||
func getMaxAndChildrenHeight(cur *Node) (h1, h2, maxh int) {
|
||||
h1 = getHeight(cur.children[0])
|
||||
h2 = getHeight(cur.children[1])
|
||||
if h1 > h2 {
|
||||
maxh = h1
|
||||
} else {
|
||||
maxh = h2
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func getMaxChildrenHeight(cur *Node) int {
|
||||
h1 := getHeight(cur.children[0])
|
||||
h2 := getHeight(cur.children[1])
|
||||
if h1 > h2 {
|
||||
return h1
|
||||
}
|
||||
return h2
|
||||
}
|
||||
|
||||
func getHeight(cur *Node) int {
|
||||
if cur == nil {
|
||||
return -1
|
||||
}
|
||||
return cur.height
|
||||
}
|
||||
|
||||
func (tree *Tree) fixRemoveHeight(cur *Node) {
|
||||
for {
|
||||
|
||||
lefth, rigthh, lrmax := getMaxAndChildrenHeight(cur)
|
||||
|
||||
// 判断当前节点是否有变化, 如果没变化的时候, 不需要往上修复
|
||||
curheight := lrmax + 1
|
||||
cur.height = curheight
|
||||
|
||||
// 计算高度的差值 绝对值大于2的时候需要旋转
|
||||
diff := lefth - rigthh
|
||||
if diff < -1 {
|
||||
r := cur.children[1] // 根据左旋转的右边节点的子节点 左右高度选择旋转的方式
|
||||
if getHeight(r.children[0]) > getHeight(r.children[1]) {
|
||||
tree.lrrotate(cur)
|
||||
} else {
|
||||
tree.lrotate(cur)
|
||||
}
|
||||
} else if diff > 1 {
|
||||
l := cur.children[0]
|
||||
if getHeight(l.children[1]) > getHeight(l.children[0]) {
|
||||
tree.rlrotate(cur)
|
||||
} else {
|
||||
tree.rrotate(cur)
|
||||
}
|
||||
} else {
|
||||
if cur.height == curheight {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if cur.parent == nil {
|
||||
return
|
||||
}
|
||||
|
||||
cur = cur.parent
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func (tree *Tree) fixPutHeight(cur *Node) {
|
||||
|
||||
for {
|
||||
|
||||
lefth := getHeight(cur.children[0])
|
||||
rigthh := getHeight(cur.children[1])
|
||||
|
||||
// 计算高度的差值 绝对值大于2的时候需要旋转
|
||||
diff := lefth - rigthh
|
||||
if diff < -1 {
|
||||
r := cur.children[1] // 根据左旋转的右边节点的子节点 左右高度选择旋转的方式
|
||||
if getHeight(r.children[0]) > getHeight(r.children[1]) {
|
||||
tree.lrrotate(cur)
|
||||
} else {
|
||||
tree.lrotate(cur)
|
||||
}
|
||||
} else if diff > 1 {
|
||||
l := cur.children[0]
|
||||
if getHeight(l.children[1]) > getHeight(l.children[0]) {
|
||||
tree.rlrotate(cur)
|
||||
} else {
|
||||
tree.rrotate(cur)
|
||||
}
|
||||
|
||||
} else {
|
||||
// 选择一个child的最大高度 + 1为 高度
|
||||
if lefth > rigthh {
|
||||
cur.height = lefth + 1
|
||||
} else {
|
||||
cur.height = rigthh + 1
|
||||
}
|
||||
}
|
||||
|
||||
if cur.parent == nil || cur.height < cur.parent.height {
|
||||
return
|
||||
}
|
||||
cur = cur.parent
|
||||
}
|
||||
}
|
||||
|
||||
func output(node *Node, prefix string, isTail bool, str *string) {
|
||||
|
||||
if node.children[1] != nil {
|
||||
newPrefix := prefix
|
||||
if isTail {
|
||||
newPrefix += "│ "
|
||||
} else {
|
||||
newPrefix += " "
|
||||
}
|
||||
output(node.children[1], newPrefix, false, str)
|
||||
}
|
||||
*str += prefix
|
||||
if isTail {
|
||||
*str += "└── "
|
||||
} else {
|
||||
*str += "┌── "
|
||||
}
|
||||
|
||||
*str += spew.Sprint(node.value) + "\n"
|
||||
|
||||
if node.children[0] != nil {
|
||||
newPrefix := prefix
|
||||
if isTail {
|
||||
newPrefix += " "
|
||||
} else {
|
||||
newPrefix += "│ "
|
||||
}
|
||||
output(node.children[0], newPrefix, true, str)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func outputfordebug(node *Node, prefix string, isTail bool, str *string) {
|
||||
|
||||
if node.children[1] != nil {
|
||||
newPrefix := prefix
|
||||
if isTail {
|
||||
newPrefix += "│ "
|
||||
} else {
|
||||
newPrefix += " "
|
||||
}
|
||||
outputfordebug(node.children[1], newPrefix, false, str)
|
||||
}
|
||||
*str += prefix
|
||||
if isTail {
|
||||
*str += "└── "
|
||||
} else {
|
||||
*str += "┌── "
|
||||
}
|
||||
|
||||
suffix := "("
|
||||
parentv := ""
|
||||
if node.parent == nil {
|
||||
parentv = "nil"
|
||||
} else {
|
||||
parentv = spew.Sprint(node.parent.value)
|
||||
}
|
||||
suffix += parentv + "|" + spew.Sprint(node.height) + ")"
|
||||
*str += spew.Sprint(node.value) + suffix + "\n"
|
||||
|
||||
if node.children[0] != nil {
|
||||
newPrefix := prefix
|
||||
if isTail {
|
||||
newPrefix += " "
|
||||
} else {
|
||||
newPrefix += "│ "
|
||||
}
|
||||
outputfordebug(node.children[0], newPrefix, true, str)
|
||||
}
|
||||
}
|
||||
|
||||
func (tree *Tree) debugString() string {
|
||||
if tree.size == 0 {
|
||||
return ""
|
||||
}
|
||||
str := "AVLTree\n"
|
||||
outputfordebug(tree.root, "", true, &str)
|
||||
return str
|
||||
}
|
||||
563
tree/avlkey/avlkey_test.go
Normal file
563
tree/avlkey/avlkey_test.go
Normal file
@@ -0,0 +1,563 @@
|
||||
package avlkey
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/gob"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"testing"
|
||||
|
||||
"474420502.top/eson/structure/compare"
|
||||
"github.com/Pallinder/go-randomdata"
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
"github.com/emirpasic/gods/trees/avltree"
|
||||
"github.com/emirpasic/gods/trees/redblacktree"
|
||||
)
|
||||
|
||||
func loadTestData() []int {
|
||||
data, err := ioutil.ReadFile("../l.log")
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
var l []int
|
||||
decoder := gob.NewDecoder(bytes.NewReader(data))
|
||||
decoder.Decode(&l)
|
||||
return l
|
||||
}
|
||||
|
||||
func TestIterator(t *testing.T) {
|
||||
tree := New(compare.Int)
|
||||
for _, v := range []int{1, 2, 7, 4, 5, 6, 7, 14, 15, 20, 30, 21, 3} {
|
||||
// t.Error(v)
|
||||
tree.Put(v, v)
|
||||
|
||||
}
|
||||
// ` AVLTree
|
||||
// │ ┌── 30
|
||||
// │ │ └── 21
|
||||
// │ ┌── 20
|
||||
// │ │ └── 15
|
||||
// └── 14
|
||||
// │ ┌── 7
|
||||
// │ ┌── 7
|
||||
// │ │ └── 6
|
||||
// └── 5
|
||||
// │ ┌── 4
|
||||
// │ │ └── 3
|
||||
// └── 2
|
||||
// └── 1`
|
||||
|
||||
iter := tree.Iterator() // root start point
|
||||
|
||||
l := []int{14, 15, 20, 21, 30}
|
||||
|
||||
for i := 0; iter.Next(); i++ {
|
||||
if iter.Value().(int) != l[i] {
|
||||
t.Error("iter Next error", iter.Value(), l[i])
|
||||
}
|
||||
}
|
||||
|
||||
iter.Next()
|
||||
if iter.Value().(int) != 30 {
|
||||
t.Error("Next == false", iter.Value(), iter.Next(), iter.Value())
|
||||
}
|
||||
|
||||
l = []int{21, 20, 15, 14, 7, 7, 6, 5, 4, 3, 2, 1}
|
||||
for i := 0; iter.Prev(); i++ { // cur is 30 next is 21
|
||||
if iter.Value().(int) != l[i] {
|
||||
t.Error(iter.Value())
|
||||
}
|
||||
}
|
||||
|
||||
if iter.Prev() != false {
|
||||
t.Error("Prev is error, cur is tail, val = 1 Prev return false")
|
||||
}
|
||||
if iter.Value().(int) != 1 { // cur is 1
|
||||
t.Error("next == false", iter.Value(), iter.Prev(), iter.Value())
|
||||
}
|
||||
|
||||
if iter.Next() != true && iter.Value().(int) != 2 {
|
||||
t.Error("next to prev is error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRange(t *testing.T) {
|
||||
tree := New(compare.Int)
|
||||
for _, v := range []int{5, 6, 8, 10, 13, 17, 1, 2, 40, 30} {
|
||||
tree.Put(v, v)
|
||||
}
|
||||
|
||||
// t.Error(tree.debugString())
|
||||
// t.Error(tree.getArountNode(20))
|
||||
// t.Error(tree.Values())
|
||||
|
||||
result := tree.GetRange(0, 20)
|
||||
if spew.Sprint(result) != "[1 2 5 6 8 10 13 17]" {
|
||||
t.Error(result)
|
||||
}
|
||||
|
||||
result = tree.GetRange(-5, -1)
|
||||
if spew.Sprint(result) != "[]" {
|
||||
t.Error(result)
|
||||
}
|
||||
|
||||
result = tree.GetRange(7, 20)
|
||||
if spew.Sprint(result) != "[8 10 13 17]" {
|
||||
t.Error(result)
|
||||
}
|
||||
|
||||
result = tree.GetRange(30, 40)
|
||||
if spew.Sprint(result) != "[30 40]" {
|
||||
t.Error(result)
|
||||
}
|
||||
|
||||
result = tree.GetRange(30, 60)
|
||||
if spew.Sprint(result) != "[30 40]" {
|
||||
t.Error(result)
|
||||
}
|
||||
|
||||
result = tree.GetRange(40, 40)
|
||||
if spew.Sprint(result) != "[40]" {
|
||||
t.Error(result)
|
||||
}
|
||||
|
||||
result = tree.GetRange(50, 60)
|
||||
if spew.Sprint(result) != "[]" {
|
||||
t.Error(result)
|
||||
}
|
||||
|
||||
result = tree.GetRange(50, 1)
|
||||
if spew.Sprint(result) != "[40 30 17 13 10 8 6 5 2 1]" {
|
||||
t.Error(result)
|
||||
}
|
||||
|
||||
result = tree.GetRange(30, 20)
|
||||
if spew.Sprint(result) != "[30]" {
|
||||
t.Error(result)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestGetAround(t *testing.T) {
|
||||
tree := New(compare.Int)
|
||||
for _, v := range []int{7, 14, 14, 14, 16, 17, 20, 30, 21, 40, 50, 3, 40, 40, 40, 15} {
|
||||
tree.Put(v, v)
|
||||
}
|
||||
|
||||
var Result string
|
||||
|
||||
Result = spew.Sprint(tree.GetAround(14))
|
||||
if Result != "[7 14 14]" {
|
||||
t.Error(tree.Values())
|
||||
t.Error("14 is root, tree.GetAround(14)) is error", Result)
|
||||
t.Error(tree.debugString())
|
||||
}
|
||||
|
||||
Result = spew.Sprint(tree.GetAround(17))
|
||||
if Result != "[16 17 20]" {
|
||||
t.Error(tree.Values())
|
||||
t.Error("tree.GetAround(17)) is error", Result)
|
||||
t.Error(tree.debugString())
|
||||
}
|
||||
|
||||
Result = spew.Sprint(tree.GetAround(3))
|
||||
if Result != "[<nil> 3 7]" {
|
||||
t.Error(tree.Values())
|
||||
t.Error("tree.GetAround(3)) is error", Result)
|
||||
t.Error(tree.debugString())
|
||||
}
|
||||
|
||||
Result = spew.Sprint(tree.GetAround(40))
|
||||
if Result != "[30 40 40]" {
|
||||
t.Error(tree.Values())
|
||||
t.Error("tree.GetAround(40)) is error", Result)
|
||||
t.Error(tree.debugString())
|
||||
}
|
||||
|
||||
Result = spew.Sprint(tree.GetAround(50))
|
||||
if Result != "[40 50 <nil>]" {
|
||||
t.Error(tree.Values())
|
||||
t.Error("tree.GetAround(50)) is error", Result)
|
||||
t.Error(tree.debugString())
|
||||
}
|
||||
|
||||
Result = spew.Sprint(tree.GetAround(18))
|
||||
if Result != "[17 <nil> 20]" {
|
||||
t.Error(tree.Values())
|
||||
t.Error("18 is not in list, tree.GetAround(18)) is error", Result)
|
||||
t.Error(tree.debugString())
|
||||
}
|
||||
|
||||
Result = spew.Sprint(tree.GetAround(5))
|
||||
if Result != "[3 <nil> 7]" {
|
||||
t.Error(tree.Values())
|
||||
t.Error("5 is not in list, tree.GetAround(5)) is error", Result)
|
||||
t.Error(tree.debugString())
|
||||
}
|
||||
|
||||
Result = spew.Sprint(tree.GetAround(2))
|
||||
if Result != "[<nil> <nil> 3]" {
|
||||
t.Error(tree.Values())
|
||||
t.Error("2 is not in list, tree.GetAround(2)) is error", Result)
|
||||
t.Error(tree.debugString())
|
||||
}
|
||||
|
||||
Result = spew.Sprint(tree.GetAround(100))
|
||||
if Result != "[50 <nil> <nil>]" {
|
||||
t.Error(tree.Values())
|
||||
t.Error("50 is not in list, tree.GetAround(50)) is error", Result)
|
||||
t.Error(tree.debugString())
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// for test error case
|
||||
func TestPutStable(t *testing.T) {
|
||||
// f, _ := os.OpenFile("./test.log", os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0666)
|
||||
// log.SetOutput(f)
|
||||
// 0-1 3 | 2-3 7-8 | 4-7 12-16 | 8-15 20-32 | 16-31 33-58 l := []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 18, 19, 20, 21, 22, 30, 41, 41, 41}
|
||||
|
||||
// tree := New(compare.Int)
|
||||
// for i := 0; i < 10; i++ {
|
||||
// tree.Put(randomdata.Number(0, 100))
|
||||
// }
|
||||
// t.Error(tree.debugString())
|
||||
|
||||
// t.Error(tree.debugString(), tree.TraversalBreadth(), "\n", "-----------")
|
||||
}
|
||||
|
||||
func TestPutComparatorRandom(t *testing.T) {
|
||||
|
||||
for n := 0; n < 300000; n++ {
|
||||
tree := New(compare.Int)
|
||||
godsavl := avltree.NewWithIntComparator()
|
||||
|
||||
content := ""
|
||||
m := make(map[int]int)
|
||||
for i := 0; len(m) < 10; i++ {
|
||||
v := randomdata.Number(0, 65535)
|
||||
if _, ok := m[v]; !ok {
|
||||
m[v] = v
|
||||
content += spew.Sprint(v) + ","
|
||||
tree.Put(v, v)
|
||||
godsavl.Put(v, v)
|
||||
}
|
||||
}
|
||||
|
||||
if tree.String() != godsavl.String() {
|
||||
t.Error(godsavl.String())
|
||||
t.Error(tree.debugString())
|
||||
t.Error(content, n)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGet(t *testing.T) {
|
||||
tree := New(compare.Int)
|
||||
for _, v := range []int{2383, 7666, 3055, 39016, 57092, 27897, 36513, 1562, 22574, 23202} {
|
||||
tree.Put(v, v)
|
||||
}
|
||||
|
||||
result := `
|
||||
│ ┌── 57092
|
||||
│ ┌── 39016
|
||||
│ │ └── 36513
|
||||
│ ┌── 27897
|
||||
│ │ │ ┌── 23202
|
||||
│ │ └── 22574
|
||||
└── 7666
|
||||
│ ┌── 3055
|
||||
└── 2383
|
||||
└── 1562
|
||||
`
|
||||
|
||||
s1 := tree.String()
|
||||
s2 := "AVLTree" + result
|
||||
if s1 != s2 {
|
||||
t.Error(s1, s2)
|
||||
}
|
||||
|
||||
for _, v := range []int{2383, 7666, 3055, 39016, 57092, 27897, 36513, 1562, 22574, 23202} {
|
||||
v, ok := tree.Get(v)
|
||||
if !ok {
|
||||
t.Error("the val not found ", v)
|
||||
}
|
||||
}
|
||||
|
||||
if v, ok := tree.Get(10000); ok {
|
||||
t.Error("the val(10000) is not in tree, but is found", v)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestRemoveAll(t *testing.T) {
|
||||
|
||||
ALL:
|
||||
for c := 0; c < 50000; c++ {
|
||||
tree := New(compare.Int)
|
||||
gods := avltree.NewWithIntComparator()
|
||||
var l []int
|
||||
m := make(map[int]int)
|
||||
|
||||
for i := 0; len(l) < 50; i++ {
|
||||
v := randomdata.Number(0, 100000)
|
||||
if _, ok := m[v]; !ok {
|
||||
m[v] = v
|
||||
l = append(l, v)
|
||||
tree.Put(v, v)
|
||||
gods.Put(v, v)
|
||||
}
|
||||
}
|
||||
|
||||
for i := 0; i < 50; i++ {
|
||||
tree.Remove(l[i])
|
||||
gods.Remove(l[i])
|
||||
s1 := spew.Sprint(tree.Values())
|
||||
s2 := spew.Sprint(gods.Values())
|
||||
if s1 != s2 {
|
||||
t.Error("avl remove error", "avlsize = ", tree.Size())
|
||||
t.Error(s1)
|
||||
t.Error(s2)
|
||||
break ALL
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestRemove(t *testing.T) {
|
||||
|
||||
ALL:
|
||||
for N := 0; N < 500000; N++ {
|
||||
tree := New(compare.Int)
|
||||
gods := avltree.NewWithIntComparator()
|
||||
|
||||
var l []int
|
||||
m := make(map[int]int)
|
||||
|
||||
for i := 0; len(l) < 10; i++ {
|
||||
v := randomdata.Number(0, 100)
|
||||
if _, ok := m[v]; !ok {
|
||||
l = append(l, v)
|
||||
m[v] = v
|
||||
tree.Put(v, v)
|
||||
gods.Put(v, v)
|
||||
}
|
||||
}
|
||||
|
||||
src1 := tree.String()
|
||||
src2 := gods.String()
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
tree.Remove(l[i])
|
||||
gods.Remove(l[i])
|
||||
if spew.Sprint(gods.Values()) != spew.Sprint(tree.Values()) && tree.size != 0 {
|
||||
// if gods.String() != tree.String() && gods.Size() != 0 && tree.size != 0 {
|
||||
t.Error(src1)
|
||||
t.Error(src2)
|
||||
t.Error(tree.debugString())
|
||||
t.Error(gods.String())
|
||||
t.Error(l[i])
|
||||
// t.Error(tree.TraversalDepth(-1))
|
||||
// t.Error(gods.Values())
|
||||
break ALL
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkIterator(b *testing.B) {
|
||||
tree := New(compare.Int)
|
||||
|
||||
l := loadTestData()
|
||||
|
||||
for _, v := range l {
|
||||
tree.Put(v, v)
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
b.StartTimer()
|
||||
b.N = 0
|
||||
iter := tree.Iterator()
|
||||
for iter.Next() {
|
||||
b.N++
|
||||
}
|
||||
for iter.Prev() {
|
||||
b.N++
|
||||
}
|
||||
for iter.Next() {
|
||||
b.N++
|
||||
}
|
||||
for iter.Prev() {
|
||||
b.N++
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func BenchmarkRemove(b *testing.B) {
|
||||
tree := New(compare.Int)
|
||||
|
||||
l := loadTestData()
|
||||
|
||||
b.N = len(l)
|
||||
for _, v := range l {
|
||||
tree.Put(v, v)
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
b.StartTimer()
|
||||
|
||||
for i := 0; i < len(l); i++ {
|
||||
tree.Remove(l[i])
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGodsRemove(b *testing.B) {
|
||||
tree := avltree.NewWithIntComparator()
|
||||
|
||||
l := loadTestData()
|
||||
|
||||
b.N = len(l)
|
||||
for _, v := range l {
|
||||
tree.Put(v, v)
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
b.StartTimer()
|
||||
|
||||
for i := 0; i < len(l); i++ {
|
||||
tree.Remove(l[i])
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGodsRBRemove(b *testing.B) {
|
||||
tree := redblacktree.NewWithIntComparator()
|
||||
|
||||
l := loadTestData()
|
||||
|
||||
b.N = len(l)
|
||||
for _, v := range l {
|
||||
tree.Put(v, v)
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
b.StartTimer()
|
||||
|
||||
for i := 0; i < len(l); i++ {
|
||||
tree.Remove(l[i])
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGet(b *testing.B) {
|
||||
|
||||
tree := New(compare.Int)
|
||||
|
||||
l := loadTestData()
|
||||
b.N = len(l)
|
||||
for i := 0; i < b.N; i++ {
|
||||
tree.Put(l[i], l[i])
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
b.StartTimer()
|
||||
|
||||
execCount := 10
|
||||
b.N = len(l) * execCount
|
||||
|
||||
for i := 0; i < execCount; i++ {
|
||||
for _, v := range l {
|
||||
tree.Get(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGodsRBGet(b *testing.B) {
|
||||
tree := redblacktree.NewWithIntComparator()
|
||||
|
||||
l := loadTestData()
|
||||
b.N = len(l)
|
||||
for i := 0; i < b.N; i++ {
|
||||
tree.Put(l[i], l[i])
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
b.StartTimer()
|
||||
|
||||
execCount := 10
|
||||
b.N = len(l) * execCount
|
||||
|
||||
for i := 0; i < execCount; i++ {
|
||||
for _, v := range l {
|
||||
tree.Get(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGodsAvlGet(b *testing.B) {
|
||||
tree := avltree.NewWithIntComparator()
|
||||
|
||||
l := loadTestData()
|
||||
b.N = len(l)
|
||||
for i := 0; i < b.N; i++ {
|
||||
tree.Put(l[i], l[i])
|
||||
}
|
||||
|
||||
b.ResetTimer()
|
||||
b.StartTimer()
|
||||
|
||||
execCount := 10
|
||||
b.N = len(l) * execCount
|
||||
|
||||
for i := 0; i < execCount; i++ {
|
||||
for _, v := range l {
|
||||
tree.Get(v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkPut(b *testing.B) {
|
||||
|
||||
l := loadTestData()
|
||||
|
||||
b.ResetTimer()
|
||||
b.StartTimer()
|
||||
|
||||
execCount := 10
|
||||
b.N = len(l) * execCount
|
||||
for i := 0; i < execCount; i++ {
|
||||
tree := New(compare.Int)
|
||||
for _, v := range l {
|
||||
tree.Put(v, v)
|
||||
}
|
||||
}
|
||||
// b.Log(tree.count)
|
||||
}
|
||||
|
||||
func BenchmarkGodsRBPut(b *testing.B) {
|
||||
tree := redblacktree.NewWithIntComparator()
|
||||
|
||||
l := loadTestData()
|
||||
|
||||
b.ResetTimer()
|
||||
b.StartTimer()
|
||||
|
||||
b.N = len(l)
|
||||
for _, v := range l {
|
||||
tree.Put(v, v)
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGodsPut(b *testing.B) {
|
||||
tree := avltree.NewWithIntComparator()
|
||||
|
||||
l := loadTestData()
|
||||
|
||||
b.ResetTimer()
|
||||
b.StartTimer()
|
||||
|
||||
b.N = len(l)
|
||||
for _, v := range l {
|
||||
tree.Put(v, v)
|
||||
}
|
||||
}
|
||||
229
tree/avlkey/iterator.go
Normal file
229
tree/avlkey/iterator.go
Normal file
@@ -0,0 +1,229 @@
|
||||
package avlkey
|
||||
|
||||
import (
|
||||
"474420502.top/eson/structure/lastack"
|
||||
)
|
||||
|
||||
type Iterator struct {
|
||||
dir int
|
||||
up *Node
|
||||
cur *Node
|
||||
tstack *lastack.Stack
|
||||
// curnext *Node
|
||||
}
|
||||
|
||||
func initIterator(avltree *Tree) *Iterator {
|
||||
iter := &Iterator{tstack: lastack.New()}
|
||||
iter.up = avltree.root
|
||||
return iter
|
||||
}
|
||||
|
||||
func NewIterator(n *Node) *Iterator {
|
||||
iter := &Iterator{tstack: lastack.New()}
|
||||
iter.up = n
|
||||
return iter
|
||||
}
|
||||
|
||||
func NewIteratorWithCap(n *Node, cap int) *Iterator {
|
||||
iter := &Iterator{tstack: lastack.NewWithCap(cap)}
|
||||
iter.up = n
|
||||
return iter
|
||||
}
|
||||
|
||||
func (iter *Iterator) SetNode(n *Node) {
|
||||
iter.up = n
|
||||
iter.dir = 0
|
||||
iter.tstack.Clear()
|
||||
}
|
||||
|
||||
func (iter *Iterator) Value() interface{} {
|
||||
return iter.cur.value
|
||||
}
|
||||
|
||||
func (iter *Iterator) Left() bool {
|
||||
if iter.cur.children[0] != nil {
|
||||
iter.dir = 0
|
||||
iter.cur = iter.cur.children[0]
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (iter *Iterator) Right() bool {
|
||||
if iter.cur.children[1] != nil {
|
||||
iter.dir = 0
|
||||
iter.cur = iter.cur.children[1]
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (iter *Iterator) GetNext(cur *Node, idx int) *Node {
|
||||
|
||||
// iter := NewIterator(cur)
|
||||
iter.SetNode(cur)
|
||||
iter.curPushNextStack(iter.up)
|
||||
iter.up = iter.getNextUp(iter.up)
|
||||
|
||||
for i := 0; i < idx; i++ {
|
||||
|
||||
if iter.tstack.Size() == 0 {
|
||||
if iter.up == nil {
|
||||
return nil
|
||||
}
|
||||
iter.tstack.Push(iter.up)
|
||||
iter.up = iter.getNextUp(iter.up)
|
||||
}
|
||||
|
||||
if v, ok := iter.tstack.Pop(); ok {
|
||||
iter.cur = v.(*Node)
|
||||
if i == idx-1 {
|
||||
return iter.cur
|
||||
}
|
||||
iter.curPushNextStack(iter.cur)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return cur
|
||||
}
|
||||
|
||||
func (iter *Iterator) Next() (result bool) {
|
||||
|
||||
if iter.dir > -1 {
|
||||
if iter.dir == 1 && 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 {
|
||||
return false
|
||||
}
|
||||
iter.tstack.Push(iter.up)
|
||||
iter.up = iter.getNextUp(iter.up)
|
||||
}
|
||||
|
||||
if v, ok := iter.tstack.Pop(); ok {
|
||||
iter.cur = v.(*Node)
|
||||
iter.curPushNextStack(iter.cur)
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
func (iter *Iterator) GetPrev(cur *Node, idx int) *Node {
|
||||
|
||||
// iter := NewIterator(cur)
|
||||
iter.SetNode(cur)
|
||||
iter.curPushPrevStack(iter.up)
|
||||
iter.up = iter.getPrevUp(iter.up)
|
||||
|
||||
for i := 0; i < idx; i++ {
|
||||
|
||||
if iter.tstack.Size() == 0 {
|
||||
if iter.up == nil {
|
||||
return nil
|
||||
}
|
||||
iter.tstack.Push(iter.up)
|
||||
iter.up = iter.getPrevUp(iter.up)
|
||||
}
|
||||
|
||||
if v, ok := iter.tstack.Pop(); ok {
|
||||
iter.cur = v.(*Node)
|
||||
if i == idx-1 {
|
||||
return iter.cur
|
||||
}
|
||||
iter.curPushPrevStack(iter.cur)
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return cur
|
||||
}
|
||||
|
||||
func (iter *Iterator) Prev() (result bool) {
|
||||
|
||||
if iter.dir < 1 { // 非 1(next 方向定义 -1 为 prev)
|
||||
if iter.dir == -1 && iter.cur != nil { // 如果上次为prev方向, 则清空辅助计算的栈
|
||||
iter.tstack.Clear()
|
||||
iter.curPushPrevStack(iter.cur) // 把当前cur计算的逆向回朔
|
||||
iter.up = iter.getPrevUp(iter.cur) // cur 寻找下个要计算up
|
||||
}
|
||||
iter.dir = 1
|
||||
}
|
||||
|
||||
// 如果栈空了, 把up的递归计算入栈, 重新计算 下次的up值
|
||||
if iter.tstack.Size() == 0 {
|
||||
if iter.up == nil {
|
||||
return false
|
||||
}
|
||||
iter.tstack.Push(iter.up)
|
||||
iter.up = iter.getPrevUp(iter.up)
|
||||
}
|
||||
|
||||
if v, ok := iter.tstack.Pop(); ok {
|
||||
iter.cur = v.(*Node)
|
||||
iter.curPushPrevStack(iter.cur)
|
||||
return true
|
||||
}
|
||||
|
||||
// 如果再次计算的栈为空, 则只能返回false
|
||||
return false
|
||||
}
|
||||
|
||||
func getRelationship(cur *Node) int {
|
||||
if cur.parent.children[1] == cur {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (iter *Iterator) getPrevUp(cur *Node) *Node {
|
||||
for cur.parent != nil {
|
||||
if getRelationship(cur) == 1 { // next 在 降序 小值. 如果child在右边, parent 比 child 小, parent才有效, 符合降序
|
||||
return cur.parent
|
||||
}
|
||||
cur = cur.parent
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (iter *Iterator) curPushPrevStack(cur *Node) {
|
||||
Prev := cur.children[0] // 当前的左然后向右找, 找到最大, 就是最接近cur 并且小于cur的值
|
||||
|
||||
if Prev != nil {
|
||||
iter.tstack.Push(Prev)
|
||||
for Prev.children[1] != nil {
|
||||
Prev = Prev.children[1]
|
||||
iter.tstack.Push(Prev) // 入栈 用于回溯
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (iter *Iterator) getNextUp(cur *Node) *Node {
|
||||
for cur.parent != nil {
|
||||
if getRelationship(cur) == 0 { // Prev 在 降序 大值. 如果child在左边, parent 比 child 大, parent才有效 , 符合降序
|
||||
return cur.parent
|
||||
}
|
||||
cur = cur.parent
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (iter *Iterator) curPushNextStack(cur *Node) {
|
||||
next := cur.children[1]
|
||||
|
||||
if next != nil {
|
||||
iter.tstack.Push(next)
|
||||
for next.children[0] != nil {
|
||||
next = next.children[0]
|
||||
iter.tstack.Push(next)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user