测试都通过, 完成avl树的基本函数架构.

This commit is contained in:
huangsimin 2019-03-14 19:14:44 +08:00
parent 2ed671254d
commit 7be4697828
12 changed files with 933 additions and 780 deletions

View File

@ -10,17 +10,9 @@ type Node struct {
children [2]*Node children [2]*Node
parent *Node parent *Node
height int height int
child int
value interface{} value interface{}
} }
// func (n *Node) String() string {
// if n == nil {
// return "nil"
// }
// return spew.Sprint(n.value)
// }
func (n *Node) String() string { func (n *Node) String() string {
if n == nil { if n == nil {
return "nil" return "nil"
@ -30,40 +22,40 @@ func (n *Node) String() string {
if n.parent != nil { if n.parent != nil {
p = spew.Sprint(n.parent.value) p = spew.Sprint(n.parent.value)
} }
return spew.Sprint(n.value) + "(" + p + "-" + spew.Sprint(n.child) + "|" + spew.Sprint(n.height) + ")" return spew.Sprint(n.value) + "(" + p + "|" + spew.Sprint(n.height) + ")"
} }
type AVL struct { type Tree struct {
root *Node root *Node
size int size int
comparator utils.Comparator comparator utils.Comparator
} }
func New(comparator utils.Comparator) *AVL { func New(comparator utils.Comparator) *Tree {
return &AVL{comparator: comparator} return &Tree{comparator: comparator}
} }
func (avl *AVL) String() string { func (avl *Tree) String() string {
if avl.size == 0 { if avl.size == 0 {
return "" return ""
} }
str := "AVLTree" + "\n" str := "AVLTree\n"
output(avl.root, "", true, &str) output(avl.root, "", true, &str)
return str return str
} }
func (avl *AVL) Iterator() *Iterator { func (avl *Tree) Iterator() *Iterator {
return initIterator(avl) return initIterator(avl)
} }
func (avl *AVL) Size() int { func (avl *Tree) Size() int {
return avl.size return avl.size
} }
func (avl *AVL) Remove(v interface{}) *Node { func (avl *Tree) Remove(key interface{}) *Node {
if n, ok := avl.GetNode(v); ok { if n, ok := avl.GetNode(key); ok {
avl.size-- avl.size--
if avl.size == 0 { if avl.size == 0 {
@ -76,7 +68,7 @@ func (avl *AVL) Remove(v interface{}) *Node {
if left == -1 && right == -1 { if left == -1 && right == -1 {
p := n.parent p := n.parent
p.children[n.child] = nil p.children[getRelationship(n)] = nil
avl.fixRemoveHeight(p) avl.fixRemoveHeight(p)
return n return n
} }
@ -89,9 +81,8 @@ func (avl *AVL) Remove(v interface{}) *Node {
} }
cleft := cur.children[0] cleft := cur.children[0]
cur.parent.children[cur.child] = cleft cur.parent.children[getRelationship(cur)] = cleft
if cleft != nil { if cleft != nil {
cleft.child = cur.child
cleft.parent = cur.parent cleft.parent = cur.parent
} }
@ -102,47 +93,49 @@ func (avl *AVL) Remove(v interface{}) *Node {
} }
cright := cur.children[1] cright := cur.children[1]
cur.parent.children[cur.child] = cright cur.parent.children[getRelationship(cur)] = cright
if cright != nil { if cright != nil {
cright.child = cur.child
cright.parent = cur.parent cright.parent = cur.parent
} }
} }
cparent := cur.parent cparent := cur.parent
avl.replace(n, cur) // 修改为interface 交换
n.value, cur.value = cur.value, n.value
// 考虑到刚好替换的节点是 被替换节点的孩子节点的时候, 从自身修复高度 // 考虑到刚好替换的节点是 被替换节点的孩子节点的时候, 从自身修复高度
if cparent == n { if cparent == n {
avl.fixRemoveHeight(cur) avl.fixRemoveHeight(n)
} else { } else {
avl.fixRemoveHeight(cparent) avl.fixRemoveHeight(cparent)
} }
return n return cur
} }
return nil return nil
} }
func (avl *AVL) Get(v interface{}) (interface{}, bool) { func (avl *Tree) Get(key interface{}) (interface{}, bool) {
n, ok := avl.GetNode(v) n, ok := avl.GetNode(key)
if ok { if ok {
return n.value, true return n.value, true
} }
return n, false return n, false
} }
func (avl *AVL) GetAround(v interface{}) (result [3]interface{}) { func (avl *Tree) GetAround(key interface{}) (result [3]interface{}) {
an := avl.GetAroundNode(v) an := avl.GetAroundNode(key)
for i, n := range an { for i, n := range an {
if n.value != nil { if n != nil {
result[i] = n.value result[i] = n.value
} }
} }
return return
} }
func (avl *AVL) GetAroundNode(v interface{}) (result [3]*Node) { func (avl *Tree) GetAroundNode(value interface{}) (result [3]*Node) {
n := avl.root n := avl.root
for { for {
@ -152,7 +145,7 @@ func (avl *AVL) GetAroundNode(v interface{}) (result [3]*Node) {
} }
lastc := 0 lastc := 0
switch c := avl.comparator(v, n.value); c { switch c := avl.comparator(value, n.value); c {
case -1: case -1:
if c != -lastc { if c != -lastc {
result[0] = n result[0] = n
@ -195,11 +188,10 @@ func (avl *AVL) GetAroundNode(v interface{}) (result [3]*Node) {
} }
} }
func (avl *AVL) GetNode(v interface{}) (*Node, bool) { func (avl *Tree) GetNode(value interface{}) (*Node, bool) {
n := avl.root for n := avl.root; n != nil; {
for n != nil { switch c := avl.comparator(value, n.value); c {
switch c := avl.comparator(v, n.value); c {
case -1: case -1:
n = n.children[0] n = n.children[0]
case 1: case 1:
@ -210,13 +202,12 @@ func (avl *AVL) GetNode(v interface{}) (*Node, bool) {
panic("Get comparator only is allowed in -1, 0, 1") panic("Get comparator only is allowed in -1, 0, 1")
} }
} }
return nil, false return nil, false
} }
func (avl *AVL) Put(v interface{}) { func (avl *Tree) Put(value interface{}) {
avl.size++ avl.size++
node := &Node{value: v} node := &Node{value: value}
if avl.size == 1 { if avl.size == 1 {
avl.root = node avl.root = node
return return
@ -231,8 +222,6 @@ func (avl *AVL) Put(v interface{}) {
if cur == nil { if cur == nil {
parent.children[child] = node parent.children[child] = node
node.parent = parent node.parent = parent
node.child = child
if node.parent.height == 0 { if node.parent.height == 0 {
avl.fixPutHeight(node.parent) avl.fixPutHeight(node.parent)
} }
@ -240,65 +229,23 @@ func (avl *AVL) Put(v interface{}) {
} }
parent = cur parent = cur
c := avl.comparator(node.value, cur.value) c := avl.comparator(value, cur.value)
if c > -1 { // right child = (c + 2) / 2
child = 1 cur = cur.children[child]
cur = cur.children[child]
} else {
child = 0
cur = cur.children[child]
}
}
}
func (avl *AVL) replace(old *Node, newN *Node) {
if old.parent == nil {
setChild(newN, 0, old.children[0])
setChild(newN, 1, old.children[1])
newN.parent = nil
newN.child = -1
newN.height = old.height
avl.root = newN
} else {
setChild(newN, 0, old.children[0])
setChild(newN, 1, old.children[1])
newN.parent = old.parent
newN.child = old.child
newN.height = old.height
old.parent.children[old.child] = newN
} }
} }
func setChild(p *Node, child int, node *Node) { func (avl *Tree) debugString() string {
p.children[child] = node
if node != nil {
node.child = child
node.parent = p
}
}
func setChildNotNil(p *Node, child int, node *Node) {
p.children[child] = node
node.child = child
node.parent = p
}
func (avl *AVL) debugString() string {
if avl.size == 0 { if avl.size == 0 {
return "" return ""
} }
str := "AVL" + "\n" str := "AVLTree\n"
outputfordebug(avl.root, "", true, &str) outputfordebug(avl.root, "", true, &str)
return str return str
} }
func (avl *AVL) TraversalBreadth() (result []interface{}) { func (avl *Tree) TraversalBreadth() (result []interface{}) {
result = make([]interface{}, 0, avl.size)
var traverasl func(cur *Node) var traverasl func(cur *Node)
traverasl = func(cur *Node) { traverasl = func(cur *Node) {
if cur == nil { if cur == nil {
@ -312,8 +259,8 @@ func (avl *AVL) TraversalBreadth() (result []interface{}) {
return return
} }
func (avl *AVL) TraversalDepth(leftright int) (result []interface{}) { func (avl *Tree) TraversalDepth(leftright int) (result []interface{}) {
result = make([]interface{}, 0, avl.size)
if leftright < 0 { if leftright < 0 {
var traverasl func(cur *Node) var traverasl func(cur *Node)
traverasl = func(cur *Node) { traverasl = func(cur *Node) {
@ -341,111 +288,148 @@ func (avl *AVL) TraversalDepth(leftright int) (result []interface{}) {
return return
} }
func (avl *AVL) lrrotate(cur *Node) *Node { func (avl *Tree) lrrotate(cur *Node) {
r := cur.children[1] const l = 1
rl := r.children[0] const r = 0
if cur.parent == nil {
avl.root = rl movparent := cur.children[l]
rl.parent = nil mov := movparent.children[r]
mov.value, cur.value = cur.value, mov.value //交换值达到, 相对位移
if mov.children[l] != nil {
movparent.children[r] = mov.children[l]
movparent.children[r].parent = movparent
//movparent.children[r].child = l
} else { } else {
setChildNotNil(cur.parent, cur.child, rl) movparent.children[r] = nil
} }
rll := rl.children[0] if mov.children[r] != nil {
rlr := rl.children[1] mov.children[l] = mov.children[r]
//mov.children[l].child = l
} else {
mov.children[l] = nil
}
setChild(cur, 1, rll) if cur.children[r] != nil {
setChild(r, 0, rlr) mov.children[r] = cur.children[r]
mov.children[r].parent = mov
} else {
mov.children[r] = nil
}
setChildNotNil(rl, 0, cur) cur.children[r] = mov
setChildNotNil(rl, 1, r) mov.parent = cur
mov.height = getMaxChildrenHeight(mov) + 1
movparent.height = getMaxChildrenHeight(movparent) + 1
cur.height = getMaxChildrenHeight(cur) + 1 cur.height = getMaxChildrenHeight(cur) + 1
r.height = getMaxChildrenHeight(r) + 1
rl.height = getMaxChildrenHeight(rl) + 1
return rl
} }
func (avl *AVL) rlrotate(cur *Node) *Node { func (avl *Tree) rlrotate(cur *Node) {
l := cur.children[0] const l = 0
lr := l.children[1] const r = 1
if cur.parent == nil {
avl.root = lr movparent := cur.children[l]
lr.parent = nil mov := movparent.children[r]
mov.value, cur.value = cur.value, mov.value //交换值达到, 相对位移
if mov.children[l] != nil {
movparent.children[r] = mov.children[l]
movparent.children[r].parent = movparent
} else { } else {
setChildNotNil(cur.parent, cur.child, lr) movparent.children[r] = nil
} }
lrr := lr.children[1] if mov.children[r] != nil {
lrl := lr.children[0] mov.children[l] = mov.children[r]
} else {
mov.children[l] = nil
}
setChild(cur, 0, lrr) if cur.children[r] != nil {
setChild(l, 1, lrl) mov.children[r] = cur.children[r]
setChildNotNil(lr, 1, cur) mov.children[r].parent = mov
setChildNotNil(lr, 0, l) } 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 cur.height = getMaxChildrenHeight(cur) + 1
l.height = getMaxChildrenHeight(l) + 1
lr.height = getMaxChildrenHeight(lr) + 1
return lr
} }
func (avl *AVL) rrotate(cur *Node) *Node { func (avl *Tree) rrotate(cur *Node) {
l := cur.children[0] const l = 0
const r = 1
// 1 right 0 left
mov := cur.children[l]
setChild(cur, 0, l.children[1]) mov.value, cur.value = cur.value, mov.value //交换值达到, 相对位移
l.parent = cur.parent // mov.children[l]不可能为nil
if cur.parent == nil { mov.children[l].parent = cur
avl.root = l cur.children[l] = mov.children[l]
// 解决mov节点孩子转移的问题
if mov.children[r] != nil {
mov.children[l] = mov.children[r]
} else { } else {
cur.parent.children[cur.child] = l mov.children[l] = nil
} }
l.child = cur.child
setChildNotNil(l, 1, cur) if cur.children[r] != nil {
// l.children[1] = cur mov.children[r] = cur.children[r]
// cur.child = 1 mov.children[r].parent = mov
// cur.parent = l } else {
mov.children[r] = nil
}
// 连接转移后的节点 由于mov只是与cur交换值,parent不变
cur.children[r] = mov
mov.height = getMaxChildrenHeight(mov) + 1
cur.height = getMaxChildrenHeight(cur) + 1 cur.height = getMaxChildrenHeight(cur) + 1
l.height = getMaxChildrenHeight(l) + 1
return l // 返回前 替换为cur节点的节点, 有利余修复高度
} }
func (avl *AVL) lrotate(cur *Node) *Node { func (avl *Tree) lrotate(cur *Node) {
r := cur.children[1] const l = 1
const r = 0
// 右左节点 链接 当前的右节点 mov := cur.children[l]
setChild(cur, 1, r.children[0])
// 设置 需要旋转的节点到当前节点的 链条 mov.value, cur.value = cur.value, mov.value //交换值达到, 相对位移
r.parent = cur.parent
if cur.parent == nil { // 不可能为nil
avl.root = r mov.children[l].parent = cur
cur.children[l] = mov.children[l]
if mov.children[r] != nil {
mov.children[l] = mov.children[r]
} else { } else {
cur.parent.children[cur.child] = r mov.children[l] = nil
} }
r.child = cur.child
// 当前节点旋转到 左边的 链条 if cur.children[r] != nil {
setChildNotNil(r, 0, cur) mov.children[r] = cur.children[r]
// r.children[0] = cur mov.children[r].parent = mov
// cur.child = 0 } else {
// cur.parent = r mov.children[r] = nil
}
// 修复改动过的节点高度 先从低开始到高 cur.children[r] = mov
mov.height = getMaxChildrenHeight(mov) + 1
cur.height = getMaxChildrenHeight(cur) + 1 cur.height = getMaxChildrenHeight(cur) + 1
r.height = getMaxChildrenHeight(r) + 1
return r
} }
func getMaxAndChildrenHeight(cur *Node) (h1, h2, maxh int) { func getMaxAndChildrenHeight(cur *Node) (h1, h2, maxh int) {
@ -476,7 +460,7 @@ func getHeight(cur *Node) int {
return cur.height return cur.height
} }
func (avl *AVL) fixRemoveHeight(cur *Node) { func (avl *Tree) fixRemoveHeight(cur *Node) {
for { for {
@ -495,16 +479,16 @@ func (avl *AVL) fixRemoveHeight(cur *Node) {
if diff < -1 { if diff < -1 {
r := cur.children[1] // 根据左旋转的右边节点的子节点 左右高度选择旋转的方式 r := cur.children[1] // 根据左旋转的右边节点的子节点 左右高度选择旋转的方式
if getHeight(r.children[0]) > getHeight(r.children[1]) { if getHeight(r.children[0]) > getHeight(r.children[1]) {
cur = avl.lrrotate(cur) avl.lrrotate(cur)
} else { } else {
cur = avl.lrotate(cur) avl.lrotate(cur)
} }
} else if diff > 1 { } else if diff > 1 {
l := cur.children[0] l := cur.children[0]
if getHeight(l.children[1]) > getHeight(l.children[0]) { if getHeight(l.children[1]) > getHeight(l.children[0]) {
cur = avl.rlrotate(cur) avl.rlrotate(cur)
} else { } else {
cur = avl.rrotate(cur) avl.rrotate(cur)
} }
} else { } else {
@ -523,7 +507,7 @@ func (avl *AVL) fixRemoveHeight(cur *Node) {
} }
func (avl *AVL) fixPutHeight(cur *Node) { func (avl *Tree) fixPutHeight(cur *Node) {
for { for {
@ -535,18 +519,18 @@ func (avl *AVL) fixPutHeight(cur *Node) {
if diff < -1 { if diff < -1 {
r := cur.children[1] // 根据左旋转的右边节点的子节点 左右高度选择旋转的方式 r := cur.children[1] // 根据左旋转的右边节点的子节点 左右高度选择旋转的方式
if getHeight(r.children[0]) > getHeight(r.children[1]) { if getHeight(r.children[0]) > getHeight(r.children[1]) {
cur = avl.lrrotate(cur) avl.lrrotate(cur)
} else { } else {
cur = avl.lrotate(cur) avl.lrotate(cur)
} }
} else if diff > 1 { } else if diff > 1 {
l := cur.children[0] l := cur.children[0]
if getHeight(l.children[1]) > getHeight(l.children[0]) { if getHeight(l.children[1]) > getHeight(l.children[0]) {
cur = avl.rlrotate(cur) avl.rlrotate(cur)
} else { } else {
cur = avl.rrotate(cur) avl.rrotate(cur)
} }
} else { } else {
// 选择一个child的最大高度 + 1为 高度 // 选择一个child的最大高度 + 1为 高度
if lefth > rigthh { if lefth > rigthh {
@ -620,7 +604,7 @@ func outputfordebug(node *Node, prefix string, isTail bool, str *string) {
} else { } else {
parentv = spew.Sprint(node.parent.value) parentv = spew.Sprint(node.parent.value)
} }
suffix += parentv + "-" + spew.Sprint(node.child) + "|" + spew.Sprint(node.height) + ")" suffix += parentv + "|" + spew.Sprint(node.height) + ")"
*str += spew.Sprint(node.value) + suffix + "\n" *str += spew.Sprint(node.value) + suffix + "\n"
if node.children[0] != nil { if node.children[0] != nil {

View File

@ -1,44 +1,60 @@
package avl package avl
import ( import (
"bytes"
"encoding/gob"
"io/ioutil"
"log" "log"
"os"
"testing" "testing"
"github.com/emirpasic/gods/maps/hashmap"
"github.com/emirpasic/gods/trees/redblacktree"
"github.com/emirpasic/gods/trees/avltree"
"github.com/davecgh/go-spew/spew"
"github.com/Pallinder/go-randomdata" "github.com/Pallinder/go-randomdata"
"github.com/davecgh/go-spew/spew"
"github.com/emirpasic/gods/trees/avltree"
"github.com/emirpasic/gods/trees/redblacktree"
"github.com/emirpasic/gods/utils" "github.com/emirpasic/gods/utils"
) )
func TestRotate(t *testing.T) { const CompartorSize = 500000
avl := New(utils.IntComparator) const NumberMax = 60000000
content := "" func TestSave(t *testing.T) {
for i := 0; i < 10; i++ {
v := randomdata.Number(0, 1000) f, err := os.OpenFile("../l.log", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
content += spew.Sprint(v) + " " if err != nil {
avl.Put(v) log.Println(err)
} }
t.Error(content) //fmt.Println(userBytes)
src := avl.String()
t.Error(src)
lsrc := avl.String() var l []int
t.Error(lsrc) m := make(map[int]int)
// rrotate(&avl.root) for i := 0; len(l) < CompartorSize; i++ {
rsrc := avl.String() v := randomdata.Number(0, NumberMax)
t.Error(rsrc) if _, ok := m[v]; !ok {
m[v] = v
if src == rsrc { l = append(l, v)
t.Error("src == rsrc") }
} }
var result bytes.Buffer
encoder := gob.NewEncoder(&result)
encoder.Encode(l)
lbytes := result.Bytes()
f.Write(lbytes)
}
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) { func TestIterator(t *testing.T) {
@ -48,88 +64,92 @@ func TestIterator(t *testing.T) {
avl.Put(v) avl.Put(v)
} }
t.Error(avl.TraversalDepth(1)) // ` AVLTree
t.Error(avl.debugString()) // │ ┌── 30
iter := avl.Iterator() // │ │ └── 21
// │ ┌── 20
// │ │ └── 15
// └── 14
// │ ┌── 7
// │ ┌── 7
// │ │ └── 6
// └── 5
// │ ┌── 4
// │ │ └── 3
// └── 2
// └── 1`
for iter.Prev() { iter := avl.Iterator() // root start point
t.Error(iter.Value())
}
t.Error("prev == false", iter.Value(), iter.Prev(), iter.Value())
for iter.Next() { l := []int{14, 15, 20, 21, 30}
t.Error(iter.Value())
}
t.Error("next == false", iter.Value(), iter.Next(), iter.Value())
for iter.Prev() { for i := 0; iter.Prev(); i++ {
t.Error(iter.Value()) if iter.Value().(int) != l[i] {
} t.Error("iter prev error", iter.Value(), l[i])
t.Error("prev == false", iter.Value())
for i := 0; iter.Next(); i++ {
t.Error(iter.Value())
if i >= 7 {
break
} }
} }
t.Error("next == false", iter.Value())
for iter.Prev() { iter.Prev()
t.Error(iter.Value()) if iter.Value().(int) != 30 {
t.Error("prev == false", iter.Value(), iter.Prev(), iter.Value())
}
l = []int{21, 20, 15, 14, 7, 7, 6, 5, 4, 3, 2, 1}
for i := 0; iter.Next(); i++ { // cur is 30 next is 21
if iter.Value().(int) != l[i] {
t.Error(iter.Value())
}
}
if iter.Next() != false {
t.Error("Next is error, cur is tail, val = 1 Next return false")
}
if iter.Value().(int) != 1 { // cur is 1
t.Error("next == false", iter.Value(), iter.Next(), iter.Value())
}
if iter.Prev() != true && iter.Value().(int) != 2 {
t.Error("next to prev is error")
} }
t.Error("prev == false", iter.Value())
} }
func TestGetAround(t *testing.T) { func TestGetAround(t *testing.T) {
avl := New(utils.IntComparator) avl := New(utils.IntComparator)
for _, v := range []int{7, 14, 15, 20, 30, 21, 40, 40, 50, 3, 40, 40, 40} { for _, v := range []int{7, 14, 15, 20, 30, 21, 40, 40, 50, 3, 40, 40, 40} {
t.Error(v)
avl.Put(v) avl.Put(v)
t.Error(avl.debugString())
} }
t.Error(avl.TraversalDepth(1))
t.Error(avl.GetAroundNode(40)) if spew.Sprint(avl.GetAround(30)) != "[40 30 21]" {
t.Error(avl.GetAround(40)) t.Error("avl.GetAround(40)) is error", spew.Sprint(avl.GetAround(30)))
}
if spew.Sprint(avl.GetAround(40)) != "[40 40 30]" {
t.Error("avl.GetAround(40)) is error", spew.Sprint(avl.GetAround(50)))
}
if spew.Sprint(avl.GetAround(50)) != "[<nil> 50 40]" {
t.Error("avl.GetAround(40)) is error", spew.Sprint(avl.GetAround(50)))
}
} }
// for test error case
func TestPutStable(t *testing.T) { func TestPutStable(t *testing.T) {
avl := New(utils.IntComparator) // avl := New(utils.IntComparator)
for _, v := range []int{7, 14, 15, 20, 30, 21} { // gods := avltree.NewWithIntComparator()
t.Error(v) // // 44908, 34985, 62991, 4201, 27210, 30707
avl.Put(v) // for _, v := range []int{2383, 7666, 3055, 39016, 57092, 27897, 36513, 1562, 22574, 23202} {
t.Error(avl.debugString()) // t.Error(v)
} // t.Error(avl.debugString())
// avl = New(utils.IntComparator) // avl.Put(v,)
// for _, v := range []int{88, 77, 80} { // gods.Put(v, v)
// avl.Put(v) // t.Error(avl.debugString())
// t.Error(avl.String()) // t.Error(gods.String())
// } // }
} }
func TestDiffPutRandom(t *testing.T) {
avl := New(utils.IntComparator)
godsavl := avltree.NewWithIntComparator()
content := ""
m := make(map[int]int)
for i := 0; len(m) < 10; i++ {
v := randomdata.Number(0, 10000)
if _, ok := m[v]; !ok {
m[v] = v
content += spew.Sprint(v) + " "
t.Error(v)
avl.Put(v)
t.Error(avl.String())
godsavl.Put(v, v)
}
}
t.Error(godsavl.String())
}
func TestPutComparatorRandom(t *testing.T) { func TestPutComparatorRandom(t *testing.T) {
for n := 0; n < 1000000; n++ { for n := 0; n < 300000; n++ {
avl := New(utils.IntComparator) avl := New(utils.IntComparator)
godsavl := avltree.NewWithIntComparator() godsavl := avltree.NewWithIntComparator()
@ -139,82 +159,95 @@ func TestPutComparatorRandom(t *testing.T) {
v := randomdata.Number(0, 65535) v := randomdata.Number(0, 65535)
if _, ok := m[v]; !ok { if _, ok := m[v]; !ok {
m[v] = v m[v] = v
content += spew.Sprint(v) + " " content += spew.Sprint(v) + ","
// t.Error(v)
avl.Put(v) avl.Put(v)
// t.Error(avl.String())
godsavl.Put(v, v) godsavl.Put(v, v)
} }
} }
if avl.String() != godsavl.String() { if avl.String() != godsavl.String() {
t.Error(godsavl.String()) t.Error(godsavl.String())
t.Error(avl.String()) t.Error(avl.debugString())
t.Error(content, n) t.Error(content, n)
break break
} }
} }
// t.Error(content)
// t.Error(avl.String())
// t.Error(godsavl.String())
// t.Error(avl.String() == godsavl.String())
} }
func TestGet(t *testing.T) { func TestGet(t *testing.T) {
avl := New(utils.IntComparator) avl := New(utils.IntComparator)
for i := 0; i < 15; i++ { for _, v := range []int{2383, 7666, 3055, 39016, 57092, 27897, 36513, 1562, 22574, 23202} {
avl.Put(randomdata.Number(0, 1000)) avl.Put(v)
} }
t.Error(avl.String())
t.Error(avl.Get(500)) result := `
57092
39016
36513
27897
23202
22574
7666
3055
2383
1562
`
s1 := avl.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 := avl.Get(v)
if !ok {
t.Error("the val not found ", v)
}
}
if v, ok := avl.Get(10000); ok {
t.Error("the val(1000) is not in tree, but is found", v)
}
} }
func TestRemoveAll(t *testing.T) { func TestRemoveAll(t *testing.T) {
for c := 0; c < 10000; c++ { ALL:
// f, _ := os.OpenFile("./out.log", os.O_TRUNC|os.O_CREATE|os.O_RDWR, 0666) for c := 0; c < 5000; c++ {
// log.SetOutput(f)
avl := New(utils.IntComparator) avl := New(utils.IntComparator)
gods := avltree.NewWithIntComparator()
var l []int var l []int
for i := 0; i < 100; i++ { m := make(map[int]int)
for i := 0; len(l) < 100; i++ {
v := randomdata.Number(0, 100000) v := randomdata.Number(0, 100000)
l = append(l, v) if _, ok := m[v]; !ok {
avl.Put(v) m[v] = v
l = append(l, v)
avl.Put(v)
gods.Put(v, v)
}
} }
// defer func() {
// if err := recover(); err != nil {
// panic(avl.String())
// }
// }()
// log.Println(avl.TraversalBreadth())
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
// log.Println(l[i])
// log.Println(avl.debugString())
avl.Remove(l[i]) avl.Remove(l[i])
gods.Remove(l[i])
s1 := spew.Sprint(avl.TraversalDepth(-1))
s2 := spew.Sprint(gods.Values())
if s1 != s2 {
t.Error("avl remove error", "avlsize = ", avl.Size())
t.Error(s1)
t.Error(s2)
break ALL
}
} }
} }
} }
func TestRemove(t *testing.T) { func TestRemove(t *testing.T) {
// avl := New(utils.IntComparator)
// var l []int
// for _, v := range []int{86, 97, 9, 61, 37, 45, 97, 43, 95, 8} {
// l = append(l, v)
// avl.Put(v)
// }
// for i := 0; i < len(l); i++ {
// // log.Println(i)
// log.Println("begin", l[i], avl.debugString())
// avl.Remove(l[i])
// log.Println("end", l[i], avl.debugString())
// }
ALL: ALL:
for N := 0; N < 500000; N++ { for N := 0; N < 500000; N++ {
avl := New(utils.IntComparator) avl := New(utils.IntComparator)
@ -249,126 +282,105 @@ ALL:
// t.Error(avl.TraversalDepth(-1)) // t.Error(avl.TraversalDepth(-1))
// t.Error(gods.Values()) // t.Error(gods.Values())
break ALL break ALL
} }
} }
} }
} }
const CompartorSize = 300000
const NumberMax = 60000000
func BenchmarkIterator(b *testing.B) { func BenchmarkIterator(b *testing.B) {
avl := New(utils.IntComparator) tree := New(utils.IntComparator)
b.N = CompartorSize
for i := 0; i < b.N; i++ { l := loadTestData()
v := randomdata.Number(0, NumberMax) b.N = len(l)
avl.Put(v)
for _, v := range l {
tree.Put(v)
} }
b.ResetTimer() b.ResetTimer()
b.StartTimer() b.StartTimer()
iter := avl.Iterator() iter := tree.Iterator()
for iter.Next() { for iter.Next() {
} }
for iter.Prev() { for iter.Prev() {
} }
for iter.Next() { for iter.Next() {
} }
} }
func BenchmarkGodsIterator(b *testing.B) { func BenchmarkGodsIterator(b *testing.B) {
avl := avltree.NewWithIntComparator() tree := avltree.NewWithIntComparator()
b.N = CompartorSize
for i := 0; i < b.N; i++ { l := loadTestData()
v := randomdata.Number(0, NumberMax) b.N = len(l)
avl.Put(v, i)
for _, v := range l {
tree.Put(v, v)
} }
b.ResetTimer() b.ResetTimer()
b.StartTimer() b.StartTimer()
iter := avl.Iterator() iter := tree.Iterator()
for iter.Next() { for iter.Next() {
} }
for iter.Prev() { for iter.Prev() {
} }
for iter.Next() { for iter.Next() {
} }
} }
func BenchmarkRemove(b *testing.B) { func BenchmarkRemove(b *testing.B) {
tree := New(utils.IntComparator)
avl := New(utils.IntComparator) l := loadTestData()
b.N = CompartorSize
var l []int b.N = len(l)
for i := 0; i < b.N; i++ { for _, v := range l {
v := randomdata.Number(0, NumberMax) tree.Put(v)
l = append(l, v)
avl.Put(v)
} }
b.ResetTimer() b.ResetTimer()
b.StartTimer() b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < len(l); i++ {
avl.Remove(l[i]) tree.Remove(l[i])
} }
} }
func BenchmarkGodsRemove(b *testing.B) { func BenchmarkGodsRemove(b *testing.B) {
avl := avltree.NewWithIntComparator() tree := avltree.NewWithIntComparator()
b.N = CompartorSize
var l []int l := loadTestData()
for i := 0; i < b.N; i++ {
v := randomdata.Number(0, NumberMax) b.N = len(l)
l = append(l, v) for _, v := range l {
avl.Put(v, v) tree.Put(v, v)
} }
b.ResetTimer() b.ResetTimer()
b.StartTimer() b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < len(l); i++ {
avl.Remove(l[i]) tree.Remove(l[i])
} }
} }
func BenchmarkGoGet(b *testing.B) { func BenchmarkGodsRBRemove(b *testing.B) {
avl := make(map[int]int) tree := redblacktree.NewWithIntComparator()
b.N = CompartorSize l := loadTestData()
for i := 0; i < b.N; i++ {
avl[randomdata.Number(0, NumberMax)] = i b.N = len(l)
for _, v := range l {
tree.Put(v, v)
} }
b.ResetTimer() b.ResetTimer()
b.StartTimer() b.StartTimer()
b.N = CompartorSize
var v int for i := 0; i < len(l); i++ {
var ok bool tree.Remove(l[i])
for i := 0; i < b.N; i++ {
v, ok = avl[randomdata.Number(0, NumberMax)]
}
if ok && v == 1 {
v = 1
} }
} }
@ -376,128 +388,81 @@ func BenchmarkGet(b *testing.B) {
avl := New(utils.IntComparator) avl := New(utils.IntComparator)
b.N = CompartorSize l := loadTestData()
for i := 0; i < b.N/2; i++ { b.N = len(l)
avl.Put(randomdata.Number(0, NumberMax))
}
b.ResetTimer() b.ResetTimer()
b.StartTimer() b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
avl.Get(randomdata.Number(0, NumberMax)) avl.Get(l[i])
} }
} }
func BenchmarkGodsRBGet(b *testing.B) { func BenchmarkGodsRBGet(b *testing.B) {
rb := redblacktree.NewWithIntComparator() tree := redblacktree.NewWithIntComparator()
b.N = CompartorSize l := loadTestData()
for i := 0; i < b.N/2; i++ { b.N = len(l)
rb.Put(randomdata.Number(0, NumberMax), i)
}
b.ResetTimer() b.ResetTimer()
b.StartTimer() b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
rb.Get(randomdata.Number(0, NumberMax)) tree.Get(l[i])
} }
} }
func BenchmarkGodsAvlGet(b *testing.B) { func BenchmarkGodsAvlGet(b *testing.B) {
rb := avltree.NewWithIntComparator() tree := avltree.NewWithIntComparator()
b.N = CompartorSize l := loadTestData()
for i := 0; i < b.N/2; i++ { b.N = len(l)
rb.Put(randomdata.Number(0, NumberMax), i)
}
b.ResetTimer() b.ResetTimer()
b.StartTimer() b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
rb.Get(randomdata.Number(0, NumberMax)) tree.Get(l[i])
} }
} }
func BenchmarkGoPut(b *testing.B) {
avl := make(map[int]int)
for i := 0; i < 100000; i++ {
avl[randomdata.Number(0, NumberMax)] = i
}
b.ResetTimer()
b.StartTimer()
b.N = CompartorSize
for i := 0; i < b.N; i++ {
avl[randomdata.Number(0, NumberMax)] = i
}
log.Println(avl[12])
}
func BenchmarkGodsHashmap(b *testing.B) {
avl := hashmap.New()
b.N = CompartorSize * 10
for i := 0; i < b.N; i++ {
avl.Put(randomdata.Number(0, NumberMax), i)
}
// b.ResetTimer()
// b.StartTimer()
// b.N = CompartorSize
// for i := 0; i < b.N; i++ {
// avl[randomdata.Number(0, NumberMax)] = i
// }
}
func BenchmarkPut(b *testing.B) { func BenchmarkPut(b *testing.B) {
avl := New(utils.IntComparator) avl := New(utils.IntComparator)
for i := 0; i < 100000; i++ { l := loadTestData()
avl.Put(randomdata.Number(0, NumberMax))
}
b.ResetTimer() b.ResetTimer()
b.StartTimer() b.StartTimer()
b.N = CompartorSize
for i := 0; i < b.N; i++ { b.N = len(l)
avl.Put(randomdata.Number(0, NumberMax)) for _, v := range l {
avl.Put(v)
} }
} }
func BenchmarkGodsRBPut(b *testing.B) { func BenchmarkGodsRBPut(b *testing.B) {
rb := redblacktree.NewWithIntComparator() tree := redblacktree.NewWithIntComparator()
for i := 0; i < 100000; i++ { l := loadTestData()
rb.Put(randomdata.Number(0, NumberMax), i)
}
b.ResetTimer() b.ResetTimer()
b.StartTimer() b.StartTimer()
b.N = CompartorSize b.N = len(l)
for i := 0; i < b.N; i++ { for _, v := range l {
rb.Put(randomdata.Number(0, NumberMax), i) tree.Put(v, v)
} }
} }
func BenchmarkGodsPut(b *testing.B) { func BenchmarkGodsPut(b *testing.B) {
avl := avltree.NewWithIntComparator() tree := avltree.NewWithIntComparator()
for i := 0; i < 100000; i++ { l := loadTestData()
avl.Put(randomdata.Number(0, NumberMax), i)
}
b.ResetTimer() b.ResetTimer()
b.StartTimer() b.StartTimer()
b.N = CompartorSize b.N = len(l)
for i := 0; i < b.N; i++ { for _, v := range l {
avl.Put(randomdata.Number(0, NumberMax), i) tree.Put(v, v)
} }
} }

View File

@ -5,7 +5,7 @@ import (
) )
type Iterator struct { type Iterator struct {
op *AVL op *Tree
dir int dir int
up *Node up *Node
@ -14,7 +14,7 @@ type Iterator struct {
// curnext *Node // curnext *Node
} }
func initIterator(avltree *AVL) *Iterator { func initIterator(avltree *Tree) *Iterator {
iter := &Iterator{op: avltree, tstack: lastack.New()} iter := &Iterator{op: avltree, tstack: lastack.New()}
iter.up = avltree.root iter.up = avltree.root
return iter return iter
@ -100,9 +100,16 @@ func (iter *Iterator) Next() (result bool) {
return false return false
} }
func getRelationship(cur *Node) int {
if cur.parent.children[1] == cur {
return 1
}
return 0
}
func (iter *Iterator) getNextUp(cur *Node) *Node { func (iter *Iterator) getNextUp(cur *Node) *Node {
for cur != nil { for cur.parent != nil {
if cur.child == 1 { // next 在 降序 小值. 如果child在右边, parent 比 child 小, parent才有效, 符合降序 if getRelationship(cur) == 1 { // next 在 降序 小值. 如果child在右边, parent 比 child 小, parent才有效, 符合降序
return cur.parent return cur.parent
} }
cur = cur.parent cur = cur.parent
@ -123,8 +130,8 @@ func (iter *Iterator) curPushNextStack(cur *Node) {
} }
func (iter *Iterator) getPrevUp(cur *Node) *Node { func (iter *Iterator) getPrevUp(cur *Node) *Node {
for cur != nil { for cur.parent != nil {
if cur.child == 0 { // Prev 在 降序 大值. 如果child在左边, parent 比 child 大, parent才有效 , 符合降序 if getRelationship(cur) == 0 { // Prev 在 降序 大值. 如果child在左边, parent 比 child 大, parent才有效 , 符合降序
return cur.parent return cur.parent
} }
cur = cur.parent cur = cur.parent

View File

@ -10,7 +10,6 @@ type Node struct {
children [2]*Node children [2]*Node
parent *Node parent *Node
height int height int
child int
value interface{} value interface{}
} }
@ -30,40 +29,40 @@ func (n *Node) String() string {
if n.parent != nil { if n.parent != nil {
p = spew.Sprint(n.parent.value) p = spew.Sprint(n.parent.value)
} }
return spew.Sprint(n.value) + "(" + p + "-" + spew.Sprint(n.child) + "|" + spew.Sprint(n.height) + ")" return spew.Sprint(n.value) + "(" + p + "|" + spew.Sprint(n.height) + ")"
} }
type AVLDup struct { type Tree struct {
root *Node root *Node
size int size int
comparator utils.Comparator comparator utils.Comparator
} }
func New(comparator utils.Comparator) *AVLDup { func New(comparator utils.Comparator) *Tree {
return &AVLDup{comparator: comparator} return &Tree{comparator: comparator}
} }
func (avl *AVLDup) String() string { func (avl *Tree) String() string {
if avl.size == 0 { if avl.size == 0 {
return "" return ""
} }
str := "AVLTree" + "\n" str := "AVLTree\n"
output(avl.root, "", true, &str) output(avl.root, "", true, &str)
return str return str
} }
func (avl *AVLDup) Iterator() *Iterator { func (avl *Tree) Iterator() *Iterator {
return initIterator(avl) return initIterator(avl)
} }
func (avl *AVLDup) Size() int { func (avl *Tree) Size() int {
return avl.size return avl.size
} }
func (avl *AVLDup) Remove(v interface{}) *Node { func (avl *Tree) Remove(value interface{}) *Node {
if n, ok := avl.GetNode(v); ok { if n, ok := avl.GetNode(value); ok {
avl.size-- avl.size--
if avl.size == 0 { if avl.size == 0 {
@ -76,7 +75,7 @@ func (avl *AVLDup) Remove(v interface{}) *Node {
if left == -1 && right == -1 { if left == -1 && right == -1 {
p := n.parent p := n.parent
p.children[n.child] = nil p.children[getRelationship(n)] = nil
avl.fixRemoveHeight(p) avl.fixRemoveHeight(p)
return n return n
} }
@ -89,9 +88,8 @@ func (avl *AVLDup) Remove(v interface{}) *Node {
} }
cleft := cur.children[0] cleft := cur.children[0]
cur.parent.children[cur.child] = cleft cur.parent.children[getRelationship(cur)] = cleft
if cleft != nil { if cleft != nil {
cleft.child = cur.child
cleft.parent = cur.parent cleft.parent = cur.parent
} }
@ -102,46 +100,49 @@ func (avl *AVLDup) Remove(v interface{}) *Node {
} }
cright := cur.children[1] cright := cur.children[1]
cur.parent.children[cur.child] = cright cur.parent.children[getRelationship(cur)] = cright
if cright != nil { if cright != nil {
cright.child = cur.child
cright.parent = cur.parent cright.parent = cur.parent
} }
} }
cparent := cur.parent cparent := cur.parent
avl.replace(n, cur) // 修改为interface 交换
n.value, cur.value = cur.value, n.value
// 考虑到刚好替换的节点是 被替换节点的孩子节点的时候, 从自身修复高度 // 考虑到刚好替换的节点是 被替换节点的孩子节点的时候, 从自身修复高度
if cparent == n { if cparent == n {
avl.fixRemoveHeight(cur) avl.fixRemoveHeight(n)
} else { } else {
avl.fixRemoveHeight(cparent) avl.fixRemoveHeight(cparent)
} }
return n return cur
} }
return nil return nil
} }
func (avl *AVLDup) Get(v interface{}) (interface{}, bool) { func (avl *Tree) Get(key interface{}) (interface{}, bool) {
n, ok := avl.GetNode(v) n, ok := avl.GetNode(key)
if ok { if ok {
return n.value, true return n.value, true
} }
return n, false return n, false
} }
func (avl *AVLDup) GetAround(v interface{}) (result [3]interface{}) { func (avl *Tree) GetAround(key interface{}) (result [3]interface{}) {
an := avl.GetAroundNode(v) an := avl.GetAroundNode(key)
for i, n := range an { for i, n := range an {
if n.value != nil { if n != nil {
result[i] = n.value result[i] = n.value
} }
} }
return return
} }
func (avl *AVLDup) GetAroundNode(v interface{}) (result [3]*Node) { func (avl *Tree) GetAroundNode(value interface{}) (result [3]*Node) {
n := avl.root n := avl.root
for { for {
@ -151,7 +152,7 @@ func (avl *AVLDup) GetAroundNode(v interface{}) (result [3]*Node) {
} }
lastc := 0 lastc := 0
switch c := avl.comparator(v, n.value); c { switch c := avl.comparator(value, n.value); c {
case -1: case -1:
if c != -lastc { if c != -lastc {
result[0] = n result[0] = n
@ -194,11 +195,10 @@ func (avl *AVLDup) GetAroundNode(v interface{}) (result [3]*Node) {
} }
} }
func (avl *AVLDup) GetNode(v interface{}) (*Node, bool) { func (avl *Tree) GetNode(value interface{}) (*Node, bool) {
n := avl.root for n := avl.root; n != nil; {
for n != nil { switch c := avl.comparator(value, n.value); c {
switch c := avl.comparator(v, n.value); c {
case -1: case -1:
n = n.children[0] n = n.children[0]
case 1: case 1:
@ -209,14 +209,13 @@ func (avl *AVLDup) GetNode(v interface{}) (*Node, bool) {
panic("Get comparator only is allowed in -1, 0, 1") panic("Get comparator only is allowed in -1, 0, 1")
} }
} }
return nil, false return nil, false
} }
func (avl *AVLDup) Put(v interface{}) { func (avl *Tree) Put(value interface{}) {
if avl.size == 0 { if avl.size == 0 {
avl.root = &Node{value: v} avl.root = &Node{value: value}
avl.size++ avl.size++
return return
} }
@ -228,12 +227,10 @@ func (avl *AVLDup) Put(v interface{}) {
for { for {
if cur == nil { if cur == nil {
node := &Node{value: v} avl.size++
node := &Node{value: value}
parent.children[child] = node parent.children[child] = node
node.parent = parent node.parent = parent
node.child = child
avl.size++
if node.parent.height == 0 { if node.parent.height == 0 {
avl.fixPutHeight(node.parent) avl.fixPutHeight(node.parent)
} }
@ -241,69 +238,24 @@ func (avl *AVLDup) Put(v interface{}) {
} }
parent = cur parent = cur
c := avl.comparator(v, cur.value) c := avl.comparator(value, cur.value)
switch c { // right child = (c + 2) / 2
case 1: cur = cur.children[child]
child = 1
cur = cur.children[child]
case -1:
child = 0
cur = cur.children[child]
case 0:
cur.value = v
return
}
} }
} }
func (avl *AVLDup) replace(old *Node, newN *Node) { func (avl *Tree) debugString() string {
if old.parent == nil {
setChild(newN, 0, old.children[0])
setChild(newN, 1, old.children[1])
newN.parent = nil
newN.child = -1
newN.height = old.height
avl.root = newN
} else {
setChild(newN, 0, old.children[0])
setChild(newN, 1, old.children[1])
newN.parent = old.parent
newN.child = old.child
newN.height = old.height
old.parent.children[old.child] = newN
}
}
func setChild(p *Node, child int, node *Node) {
p.children[child] = node
if node != nil {
node.child = child
node.parent = p
}
}
func setChildNotNil(p *Node, child int, node *Node) {
p.children[child] = node
node.child = child
node.parent = p
}
func (avl *AVLDup) debugString() string {
if avl.size == 0 { if avl.size == 0 {
return "" return ""
} }
str := "AVLDup" + "\n" str := "AVLTree\n"
outputfordebug(avl.root, "", true, &str) outputfordebug(avl.root, "", true, &str)
return str return str
} }
func (avl *AVLDup) TraversalBreadth() (result []interface{}) { func (avl *Tree) TraversalBreadth() (result []interface{}) {
result = make([]interface{}, 0, avl.size)
var traverasl func(cur *Node) var traverasl func(cur *Node)
traverasl = func(cur *Node) { traverasl = func(cur *Node) {
if cur == nil { if cur == nil {
@ -317,8 +269,8 @@ func (avl *AVLDup) TraversalBreadth() (result []interface{}) {
return return
} }
func (avl *AVLDup) TraversalDepth(leftright int) (result []interface{}) { func (avl *Tree) TraversalDepth(leftright int) (result []interface{}) {
result = make([]interface{}, 0, avl.size)
if leftright < 0 { if leftright < 0 {
var traverasl func(cur *Node) var traverasl func(cur *Node)
traverasl = func(cur *Node) { traverasl = func(cur *Node) {
@ -346,111 +298,162 @@ func (avl *AVLDup) TraversalDepth(leftright int) (result []interface{}) {
return return
} }
func (avl *AVLDup) lrrotate(cur *Node) *Node { func (avl *Tree) lrrotate(cur *Node) {
r := cur.children[1] const l = 1
rl := r.children[0] const r = 0
if cur.parent == nil {
avl.root = rl movparent := cur.children[l]
rl.parent = nil mov := movparent.children[r]
mov.value, cur.value = cur.value, mov.value //交换值达到, 相对位移
if mov.children[l] != nil {
movparent.children[r] = mov.children[l]
movparent.children[r].parent = movparent
//movparent.children[r].child = l
} else { } else {
setChildNotNil(cur.parent, cur.child, rl) movparent.children[r] = nil
} }
rll := rl.children[0] if mov.children[r] != nil {
rlr := rl.children[1] mov.children[l] = mov.children[r]
//mov.children[l].child = l
} else {
mov.children[l] = nil
}
setChild(cur, 1, rll) if cur.children[r] != nil {
setChild(r, 0, rlr) mov.children[r] = cur.children[r]
mov.children[r].parent = mov
} else {
mov.children[r] = nil
}
setChildNotNil(rl, 0, cur) cur.children[r] = mov
setChildNotNil(rl, 1, r) mov.parent = cur
mov.height = getMaxChildrenHeight(mov) + 1
movparent.height = getMaxChildrenHeight(movparent) + 1
cur.height = getMaxChildrenHeight(cur) + 1 cur.height = getMaxChildrenHeight(cur) + 1
r.height = getMaxChildrenHeight(r) + 1
rl.height = getMaxChildrenHeight(rl) + 1
return rl
} }
func (avl *AVLDup) rlrotate(cur *Node) *Node { func (avl *Tree) rlrotate(cur *Node) {
l := cur.children[0] const l = 0
lr := l.children[1] const r = 1
if cur.parent == nil {
avl.root = lr movparent := cur.children[l]
lr.parent = nil mov := movparent.children[r]
mov.value, cur.value = cur.value, mov.value //交换值达到, 相对位移
if mov.children[l] != nil {
movparent.children[r] = mov.children[l]
movparent.children[r].parent = movparent
} else { } else {
setChildNotNil(cur.parent, cur.child, lr) movparent.children[r] = nil
} }
lrr := lr.children[1] if mov.children[r] != nil {
lrl := lr.children[0] mov.children[l] = mov.children[r]
} else {
mov.children[l] = nil
}
setChild(cur, 0, lrr) if cur.children[r] != nil {
setChild(l, 1, lrl) mov.children[r] = cur.children[r]
setChildNotNil(lr, 1, cur) mov.children[r].parent = mov
setChildNotNil(lr, 0, l) } 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 cur.height = getMaxChildrenHeight(cur) + 1
l.height = getMaxChildrenHeight(l) + 1
lr.height = getMaxChildrenHeight(lr) + 1
return lr
} }
func (avl *AVLDup) rrotate(cur *Node) *Node { func (avl *Tree) rrotate(cur *Node) {
l := cur.children[0] const l = 0
const r = 1
// 1 right 0 left
mov := cur.children[l]
setChild(cur, 0, l.children[1]) mov.value, cur.value = cur.value, mov.value //交换值达到, 相对位移
l.parent = cur.parent // if mov.children[l] != nil {
if cur.parent == nil { // mov.children[l].parent = cur
avl.root = l // cur.children[l] = mov.children[l]
// } else {
// cur.children[l] = nil
// }
// 不可能为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 { } else {
cur.parent.children[cur.child] = l mov.children[l] = nil
} }
l.child = cur.child
setChildNotNil(l, 1, cur) if cur.children[r] != nil {
// l.children[1] = cur mov.children[r] = cur.children[r]
// cur.child = 1 mov.children[r].parent = mov
// cur.parent = l } else {
mov.children[r] = nil
}
// 连接转移后的节点 由于mov只是与cur交换值,parent不变
cur.children[r] = mov
mov.height = getMaxChildrenHeight(mov) + 1
cur.height = getMaxChildrenHeight(cur) + 1 cur.height = getMaxChildrenHeight(cur) + 1
l.height = getMaxChildrenHeight(l) + 1
return l // 返回前 替换为cur节点的节点, 有利余修复高度
} }
func (avl *AVLDup) lrotate(cur *Node) *Node { func (avl *Tree) lrotate(cur *Node) {
r := cur.children[1] const l = 1
const r = 0
// 右左节点 链接 当前的右节点 mov := cur.children[l]
setChild(cur, 1, r.children[0])
// 设置 需要旋转的节点到当前节点的 链条 mov.value, cur.value = cur.value, mov.value //交换值达到, 相对位移
r.parent = cur.parent
if cur.parent == nil { // if mov.children[l] != nil {
avl.root = r // mov.children[l].parent = cur
// cur.children[l] = mov.children[l]
// } else {
// cur.children[l] = nil
// }
// 不可能为nil
mov.children[l].parent = cur
cur.children[l] = mov.children[l]
if mov.children[r] != nil {
mov.children[l] = mov.children[r]
} else { } else {
cur.parent.children[cur.child] = r mov.children[l] = nil
} }
r.child = cur.child
// 当前节点旋转到 左边的 链条 if cur.children[r] != nil {
setChildNotNil(r, 0, cur) mov.children[r] = cur.children[r]
// r.children[0] = cur mov.children[r].parent = mov
// cur.child = 0 } else {
// cur.parent = r mov.children[r] = nil
}
// 修复改动过的节点高度 先从低开始到高 cur.children[r] = mov
mov.height = getMaxChildrenHeight(mov) + 1
cur.height = getMaxChildrenHeight(cur) + 1 cur.height = getMaxChildrenHeight(cur) + 1
r.height = getMaxChildrenHeight(r) + 1
return r
} }
func getMaxAndChildrenHeight(cur *Node) (h1, h2, maxh int) { func getMaxAndChildrenHeight(cur *Node) (h1, h2, maxh int) {
@ -481,7 +484,7 @@ func getHeight(cur *Node) int {
return cur.height return cur.height
} }
func (avl *AVLDup) fixRemoveHeight(cur *Node) { func (avl *Tree) fixRemoveHeight(cur *Node) {
for { for {
@ -500,16 +503,16 @@ func (avl *AVLDup) fixRemoveHeight(cur *Node) {
if diff < -1 { if diff < -1 {
r := cur.children[1] // 根据左旋转的右边节点的子节点 左右高度选择旋转的方式 r := cur.children[1] // 根据左旋转的右边节点的子节点 左右高度选择旋转的方式
if getHeight(r.children[0]) > getHeight(r.children[1]) { if getHeight(r.children[0]) > getHeight(r.children[1]) {
cur = avl.lrrotate(cur) avl.lrrotate(cur)
} else { } else {
cur = avl.lrotate(cur) avl.lrotate(cur)
} }
} else if diff > 1 { } else if diff > 1 {
l := cur.children[0] l := cur.children[0]
if getHeight(l.children[1]) > getHeight(l.children[0]) { if getHeight(l.children[1]) > getHeight(l.children[0]) {
cur = avl.rlrotate(cur) avl.rlrotate(cur)
} else { } else {
cur = avl.rrotate(cur) avl.rrotate(cur)
} }
} else { } else {
@ -528,7 +531,7 @@ func (avl *AVLDup) fixRemoveHeight(cur *Node) {
} }
func (avl *AVLDup) fixPutHeight(cur *Node) { func (avl *Tree) fixPutHeight(cur *Node) {
for { for {
@ -540,18 +543,18 @@ func (avl *AVLDup) fixPutHeight(cur *Node) {
if diff < -1 { if diff < -1 {
r := cur.children[1] // 根据左旋转的右边节点的子节点 左右高度选择旋转的方式 r := cur.children[1] // 根据左旋转的右边节点的子节点 左右高度选择旋转的方式
if getHeight(r.children[0]) > getHeight(r.children[1]) { if getHeight(r.children[0]) > getHeight(r.children[1]) {
cur = avl.lrrotate(cur) avl.lrrotate(cur)
} else { } else {
cur = avl.lrotate(cur) avl.lrotate(cur)
} }
} else if diff > 1 { } else if diff > 1 {
l := cur.children[0] l := cur.children[0]
if getHeight(l.children[1]) > getHeight(l.children[0]) { if getHeight(l.children[1]) > getHeight(l.children[0]) {
cur = avl.rlrotate(cur) avl.rlrotate(cur)
} else { } else {
cur = avl.rrotate(cur) avl.rrotate(cur)
} }
} else { } else {
// 选择一个child的最大高度 + 1为 高度 // 选择一个child的最大高度 + 1为 高度
if lefth > rigthh { if lefth > rigthh {
@ -625,7 +628,7 @@ func outputfordebug(node *Node, prefix string, isTail bool, str *string) {
} else { } else {
parentv = spew.Sprint(node.parent.value) parentv = spew.Sprint(node.parent.value)
} }
suffix += parentv + "-" + spew.Sprint(node.child) + "|" + spew.Sprint(node.height) + ")" suffix += parentv + "|" + spew.Sprint(node.height) + ")"
*str += spew.Sprint(node.value) + suffix + "\n" *str += spew.Sprint(node.value) + suffix + "\n"
if node.children[0] != nil { if node.children[0] != nil {

View File

@ -1,173 +1,297 @@
package avldup package avldup
import ( import (
"bytes"
"encoding/gob"
"io/ioutil"
"log"
"os"
"testing" "testing"
"github.com/emirpasic/gods/trees/redblacktree"
"github.com/emirpasic/gods/trees/avltree"
"github.com/davecgh/go-spew/spew"
"github.com/Pallinder/go-randomdata" "github.com/Pallinder/go-randomdata"
"github.com/davecgh/go-spew/spew"
"github.com/emirpasic/gods/trees/avltree"
"github.com/emirpasic/gods/trees/redblacktree"
"github.com/emirpasic/gods/utils" "github.com/emirpasic/gods/utils"
) )
func TestRotate(t *testing.T) { const CompartorSize = 500000
avl := New(utils.IntComparator) const NumberMax = 60000000
content := "" func TestSave(t *testing.T) {
for i := 0; i < 10; i++ {
v := randomdata.Number(0, 1000) f, err := os.OpenFile("../l.log", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
content += spew.Sprint(v) + " " if err != nil {
avl.Put(v) log.Println(err)
} }
t.Error(content) //fmt.Println(userBytes)
src := avl.String()
t.Error(src)
lsrc := avl.String() var l []int
t.Error(lsrc)
// rrotate(&avl.root)
rsrc := avl.String()
t.Error(rsrc)
if src == rsrc {
t.Error("src == rsrc")
}
}
func TestPutStable(t *testing.T) {
avl := New(utils.IntComparator)
for _, v := range []int{7, 14, 15, 20, 30, 21, 7} {
t.Error(v)
avl.Put(v)
t.Error(avl.debugString())
}
// avl = New(utils.IntComparator)
// for _, v := range []int{88, 77, 80} {
// avl.Put(v)
// t.Error(avl.String())
// }
}
func TestDiffPutRandom(t *testing.T) {
avl := New(utils.IntComparator)
godsavl := avltree.NewWithIntComparator()
content := ""
m := make(map[int]int) m := make(map[int]int)
for i := 0; len(m) < 10; i++ { for i := 0; len(l) < CompartorSize; i++ {
v := randomdata.Number(0, 10000) v := randomdata.Number(0, NumberMax)
if _, ok := m[v]; !ok { if _, ok := m[v]; !ok {
m[v] = v m[v] = v
content += spew.Sprint(v) + " " l = append(l, v)
t.Error(v)
avl.Put(v)
t.Error(avl.String())
godsavl.Put(v, v)
} }
} }
t.Error(godsavl.String())
var result bytes.Buffer
encoder := gob.NewEncoder(&result)
encoder.Encode(l)
lbytes := result.Bytes()
f.Write(lbytes)
}
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 TestDupKey(t *testing.T) {
tree1 := New(utils.IntComparator)
tree2 := avltree.NewWithIntComparator()
for i := 0; i < CompartorSize/1000; i++ {
v := randomdata.Number(0, NumberMax)
tree1.Put(v)
tree2.Put(v, v)
}
tree1.Put(500)
tree2.Put(500, 500)
tree1.Put(500)
tree2.Put(500, 500)
if tree1.Size() == tree2.Size() {
t.Error("tree size is equal")
}
if tree1.String() == tree2.String() {
t.Error(tree1.String())
}
}
func TestIterator(t *testing.T) {
avl := New(utils.IntComparator)
for _, v := range []int{1, 2, 7, 4, 5, 6, 7, 14, 15, 20, 30, 21, 3} {
// t.Error(v)
avl.Put(v)
}
// ` AVLTree
// │ ┌── 30
// │ │ └── 21
// │ ┌── 20
// │ │ └── 15
// └── 14
// │ ┌── 7
// │ ┌── 7
// │ │ └── 6
// └── 5
// │ ┌── 4
// │ │ └── 3
// └── 2
// └── 1`
iter := avl.Iterator() // root start point
l := []int{14, 15, 20, 21, 30}
for i := 0; iter.Prev(); i++ {
if iter.Value().(int) != l[i] {
t.Error("iter prev error", iter.Value(), l[i])
}
}
iter.Prev()
if iter.Value().(int) != 30 {
t.Error("prev == false", iter.Value(), iter.Prev(), iter.Value())
}
l = []int{21, 20, 15, 14, 7, 7, 6, 5, 4, 3, 2, 1}
for i := 0; iter.Next(); i++ { // cur is 30 next is 21
if iter.Value().(int) != l[i] {
t.Error(iter.Value())
}
}
if iter.Next() != false {
t.Error("Next is error, cur is tail, val = 1 Next return false")
}
if iter.Value().(int) != 1 { // cur is 1
t.Error("next == false", iter.Value(), iter.Next(), iter.Value())
}
if iter.Prev() != true && iter.Value().(int) != 2 {
t.Error("next to prev is error")
}
}
func TestGetAround(t *testing.T) {
avl := New(utils.IntComparator)
for _, v := range []int{7, 14, 15, 20, 30, 21, 40, 40, 50, 3, 40, 40, 40} {
avl.Put(v)
}
if spew.Sprint(avl.GetAround(30)) != "[40 30 21]" {
t.Error("avl.GetAround(40)) is error", spew.Sprint(avl.GetAround(30)))
}
if spew.Sprint(avl.GetAround(40)) != "[40 40 30]" {
t.Error("avl.GetAround(40)) is error", spew.Sprint(avl.GetAround(50)))
}
if spew.Sprint(avl.GetAround(50)) != "[<nil> 50 40]" {
t.Error("avl.GetAround(40)) is error", spew.Sprint(avl.GetAround(50)))
}
}
// for test error case
func TestPutStable(t *testing.T) {
// avl := New(utils.IntComparator)
// gods := avltree.NewWithIntComparator()
// // 44908, 34985, 62991, 4201, 27210, 30707
// for _, v := range []int{2383, 7666, 3055, 39016, 57092, 27897, 36513, 1562, 22574, 23202} {
// t.Error(v)
// t.Error(avl.debugString())
// avl.Put(v)
// gods.Put(v, v)
// t.Error(avl.debugString())
// t.Error(gods.String())
// }
} }
func TestPutComparatorRandom(t *testing.T) { func TestPutComparatorRandom(t *testing.T) {
for n := 0; n < 1000000; n++ { for n := 0; n < 300000; n++ {
avl := New(utils.IntComparator) avl := New(utils.IntComparator)
godsavl := avltree.NewWithIntComparator() godsavl := avltree.NewWithIntComparator()
content := "" content := ""
for i := 0; avl.size < 10; i++ { m := make(map[int]int)
for i := 0; len(m) < 10; i++ {
v := randomdata.Number(0, 65535) v := randomdata.Number(0, 65535)
content += spew.Sprint(v) + " " if _, ok := m[v]; !ok {
avl.Put(v) m[v] = v
godsavl.Put(v, v) content += spew.Sprint(v) + ","
// t.Error(v)
avl.Put(v)
// t.Error(avl.String())
godsavl.Put(v, v)
}
} }
if avl.String() != godsavl.String() { if avl.String() != godsavl.String() {
t.Error(content) t.Error(godsavl.String())
t.Error(avl.debugString())
t.Error(content, n)
break break
} }
} }
// t.Error(content)
// t.Error(avl.String())
// t.Error(godsavl.String())
// t.Error(avl.String() == godsavl.String())
} }
func TestGet(t *testing.T) { func TestGet(t *testing.T) {
avl := New(utils.IntComparator) avl := New(utils.IntComparator)
for i := 0; i < 15; i++ { for _, v := range []int{2383, 7666, 3055, 39016, 57092, 27897, 36513, 1562, 22574, 23202} {
avl.Put(randomdata.Number(0, 1000)) avl.Put(v)
} }
t.Error(avl.String())
t.Error(avl.Get(500)) result := `
57092
39016
36513
27897
23202
22574
7666
3055
2383
1562
`
s1 := avl.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 := avl.Get(v)
if !ok {
t.Error("the val not found ", v)
}
}
if v, ok := avl.Get(10000); ok {
t.Error("the val(1000) is not in tree, but is found", v)
}
} }
func TestRemoveAll(t *testing.T) { func TestRemoveAll(t *testing.T) {
for c := 0; c < 10000; c++ { ALL:
// f, _ := os.OpenFile("./out.log", os.O_TRUNC|os.O_CREATE|os.O_RDWR, 0666) for c := 0; c < 5000; c++ {
// log.SetOutput(f)
avl := New(utils.IntComparator) avl := New(utils.IntComparator)
gods := avltree.NewWithIntComparator()
var l []int var l []int
for i := 0; i < 100; i++ { m := make(map[int]int)
for i := 0; len(l) < 100; i++ {
v := randomdata.Number(0, 100000) v := randomdata.Number(0, 100000)
l = append(l, v) if _, ok := m[v]; !ok {
avl.Put(v) m[v] = v
l = append(l, v)
avl.Put(v)
gods.Put(v, v)
}
} }
// defer func() {
// if err := recover(); err != nil {
// panic(avl.String())
// }
// }()
// log.Println(avl.TraversalBreadth())
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
// log.Println(l[i])
// log.Println(avl.debugString())
avl.Remove(l[i]) avl.Remove(l[i])
gods.Remove(l[i])
s1 := spew.Sprint(avl.TraversalDepth(-1))
s2 := spew.Sprint(gods.Values())
if s1 != s2 {
t.Error("avl remove error", "avlsize = ", avl.Size())
t.Error(s1)
t.Error(s2)
break ALL
}
} }
} }
} }
func TestRemove(t *testing.T) { func TestRemove(t *testing.T) {
// avl := New(utils.IntComparator)
// var l []int
// for _, v := range []int{86, 97, 9, 61, 37, 45, 97, 43, 95, 8} {
// l = append(l, v)
// avl.Put(v)
// }
// for i := 0; i < len(l); i++ {
// // log.Println(i)
// log.Println("begin", l[i], avl.debugString())
// avl.Remove(l[i])
// log.Println("end", l[i], avl.debugString())
// }
ALL: ALL:
for N := 0; N < 500000; N++ { for N := 0; N < 500000; N++ {
avl := New(utils.IntComparator) avl := New(utils.IntComparator)
gods := avltree.NewWithIntComparator() gods := avltree.NewWithIntComparator()
var l []int var l []int
m := make(map[int]int)
for i := 0; avl.size < 10; i++ { for i := 0; len(l) < 10; i++ {
v := randomdata.Number(0, 100) v := randomdata.Number(0, 100)
if _, ok := m[v]; !ok {
l = append(l, v) l = append(l, v)
avl.Put(v) m[v] = v
gods.Put(v, v) avl.Put(v)
gods.Put(v, v)
}
} }
src1 := avl.String() src1 := avl.String()
@ -186,124 +310,187 @@ ALL:
// t.Error(avl.TraversalDepth(-1)) // t.Error(avl.TraversalDepth(-1))
// t.Error(gods.Values()) // t.Error(gods.Values())
break ALL break ALL
} }
} }
} }
} }
const PutCompartorSize = 300000 func BenchmarkIterator(b *testing.B) {
const NumberMax = 60000000 tree := New(utils.IntComparator)
l := loadTestData()
b.N = len(l)
for _, v := range l {
tree.Put(v)
}
b.ResetTimer()
b.StartTimer()
iter := tree.Iterator()
for iter.Next() {
}
for iter.Prev() {
}
for iter.Next() {
}
}
func BenchmarkGodsIterator(b *testing.B) {
tree := avltree.NewWithIntComparator()
l := loadTestData()
b.N = len(l)
for _, v := range l {
tree.Put(v, v)
}
b.ResetTimer()
b.StartTimer()
iter := tree.Iterator()
for iter.Next() {
}
for iter.Prev() {
}
for iter.Next() {
}
}
func BenchmarkRemove(b *testing.B) { func BenchmarkRemove(b *testing.B) {
tree := New(utils.IntComparator)
avl := New(utils.IntComparator) l := loadTestData()
b.N = PutCompartorSize
var l []int b.N = len(l)
for i := 0; i < b.N; i++ { for _, v := range l {
v := randomdata.Number(0, NumberMax) tree.Put(v)
l = append(l, v)
avl.Put(v)
} }
b.ResetTimer() b.ResetTimer()
b.StartTimer() b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < len(l); i++ {
avl.Remove(l[i]) tree.Remove(l[i])
} }
} }
func BenchmarkGodsRemove(b *testing.B) { func BenchmarkGodsRemove(b *testing.B) {
avl := avltree.NewWithIntComparator() tree := avltree.NewWithIntComparator()
b.N = PutCompartorSize
var l []int l := loadTestData()
for i := 0; i < b.N; i++ {
v := randomdata.Number(0, NumberMax) b.N = len(l)
l = append(l, v) for _, v := range l {
avl.Put(v, v) tree.Put(v, v)
} }
b.ResetTimer() b.ResetTimer()
b.StartTimer() b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < len(l); i++ {
avl.Remove(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) { func BenchmarkGet(b *testing.B) {
avl := New(utils.IntComparator) avl := New(utils.IntComparator)
b.N = PutCompartorSize l := loadTestData()
for i := 0; i < b.N/2; i++ { b.N = len(l)
avl.Put(randomdata.Number(0, NumberMax))
}
b.ResetTimer() b.ResetTimer()
b.StartTimer() b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
avl.Get(randomdata.Number(0, NumberMax)) avl.Get(l[i])
} }
} }
func BenchmarkGodsRBGet(b *testing.B) { func BenchmarkGodsRBGet(b *testing.B) {
rb := redblacktree.NewWithIntComparator() tree := redblacktree.NewWithIntComparator()
b.N = PutCompartorSize l := loadTestData()
for i := 0; i < b.N/2; i++ { b.N = len(l)
rb.Put(randomdata.Number(0, NumberMax), i)
}
b.ResetTimer() b.ResetTimer()
b.StartTimer() b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
rb.Get(randomdata.Number(0, NumberMax)) tree.Get(l[i])
} }
} }
func BenchmarkGodsAvlGet(b *testing.B) { func BenchmarkGodsAvlGet(b *testing.B) {
rb := avltree.NewWithIntComparator() tree := avltree.NewWithIntComparator()
b.N = PutCompartorSize l := loadTestData()
for i := 0; i < b.N/2; i++ { b.N = len(l)
rb.Put(randomdata.Number(0, NumberMax), i)
}
b.ResetTimer() b.ResetTimer()
b.StartTimer() b.StartTimer()
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
rb.Get(randomdata.Number(0, NumberMax)) tree.Get(l[i])
} }
} }
func BenchmarkPut(b *testing.B) { func BenchmarkPut(b *testing.B) {
avl := New(utils.IntComparator) avl := New(utils.IntComparator)
b.N = PutCompartorSize l := loadTestData()
for i := 0; i < b.N; i++ {
avl.Put(randomdata.Number(0, NumberMax)) b.ResetTimer()
b.StartTimer()
b.N = len(l)
for _, v := range l {
avl.Put(v)
} }
} }
func BenchmarkGodsRBPut(b *testing.B) { func BenchmarkGodsRBPut(b *testing.B) {
rb := redblacktree.NewWithIntComparator() tree := redblacktree.NewWithIntComparator()
b.N = PutCompartorSize l := loadTestData()
for i := 0; i < b.N; i++ {
rb.Put(randomdata.Number(0, NumberMax), i) b.ResetTimer()
b.StartTimer()
b.N = len(l)
for _, v := range l {
tree.Put(v, v)
} }
} }
func BenchmarkGodsPut(b *testing.B) { func BenchmarkGodsPut(b *testing.B) {
avl := avltree.NewWithIntComparator() tree := avltree.NewWithIntComparator()
b.N = PutCompartorSize l := loadTestData()
for i := 0; i < b.N; i++ {
avl.Put(randomdata.Number(0, NumberMax), i) b.ResetTimer()
b.StartTimer()
b.N = len(l)
for _, v := range l {
tree.Put(v, v)
} }
} }

View File

@ -5,7 +5,7 @@ import (
) )
type Iterator struct { type Iterator struct {
op *AVLDup op *Tree
dir int dir int
up *Node up *Node
@ -14,7 +14,7 @@ type Iterator struct {
// curnext *Node // curnext *Node
} }
func initIterator(avltree *AVLDup) *Iterator { func initIterator(avltree *Tree) *Iterator {
iter := &Iterator{op: avltree, tstack: lastack.New()} iter := &Iterator{op: avltree, tstack: lastack.New()}
iter.up = avltree.root iter.up = avltree.root
return iter return iter
@ -100,9 +100,16 @@ func (iter *Iterator) Next() (result bool) {
return false return false
} }
func getRelationship(cur *Node) int {
if cur.parent.children[1] == cur {
return 1
}
return 0
}
func (iter *Iterator) getNextUp(cur *Node) *Node { func (iter *Iterator) getNextUp(cur *Node) *Node {
for cur != nil { for cur.parent != nil {
if cur.child == 1 { // next 在 降序 小值. 如果child在右边, parent 比 child 小, parent才有效, 符合降序 if getRelationship(cur) == 1 { // next 在 降序 小值. 如果child在右边, parent 比 child 小, parent才有效, 符合降序
return cur.parent return cur.parent
} }
cur = cur.parent cur = cur.parent
@ -123,8 +130,8 @@ func (iter *Iterator) curPushNextStack(cur *Node) {
} }
func (iter *Iterator) getPrevUp(cur *Node) *Node { func (iter *Iterator) getPrevUp(cur *Node) *Node {
for cur != nil { for cur.parent != nil {
if cur.child == 0 { // Prev 在 降序 大值. 如果child在左边, parent 比 child 大, parent才有效 , 符合降序 if getRelationship(cur) == 0 { // Prev 在 降序 大值. 如果child在左边, parent 比 child 大, parent才有效 , 符合降序
return cur.parent return cur.parent
} }
cur = cur.parent cur = cur.parent

View File

@ -1,4 +1,4 @@
package avl package avlkey
import ( import (
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"

View File

@ -1,4 +1,4 @@
package avl package avlkey
import ( import (
"bytes" "bytes"

View File

@ -1,4 +1,4 @@
package avl package avlkey
import ( import (
"474420502.top/eson/structure/lastack" "474420502.top/eson/structure/lastack"

View File

@ -1,4 +1,4 @@
package avl package avlkeydup
import ( import (
"github.com/davecgh/go-spew/spew" "github.com/davecgh/go-spew/spew"

View File

@ -1,4 +1,4 @@
package avl package avlkeydup
import ( import (
"bytes" "bytes"

View File

@ -1,4 +1,4 @@
package avl package avlkeydup
import ( import (
"474420502.top/eson/structure/lastack" "474420502.top/eson/structure/lastack"