|
|
|
@ -5,6 +5,8 @@
|
|
|
|
|
// Package avltree implements an AVL balanced binary tree.
|
|
|
|
|
//
|
|
|
|
|
// Structure is not thread safe.
|
|
|
|
|
//
|
|
|
|
|
// References: https://en.wikipedia.org/wiki/AVL_tree
|
|
|
|
|
package avltree
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
@ -144,8 +146,10 @@ func (t *Tree) Ceiling(key interface{}) (floor *Node, found bool) {
|
|
|
|
|
// Put inserts node into the tree.
|
|
|
|
|
// Key should adhere to the comparator's type assertion, otherwise method panics.
|
|
|
|
|
func (t *Tree) Put(key interface{}, value interface{}) {
|
|
|
|
|
var put func(*Node, **Node) bool
|
|
|
|
|
put = func(p *Node, qp **Node) bool {
|
|
|
|
|
t.put(key, value, nil, &t.Root)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (t *Tree) put(key interface{}, value interface{}, p *Node, qp **Node) bool {
|
|
|
|
|
q := *qp
|
|
|
|
|
if q == nil {
|
|
|
|
|
t.size++
|
|
|
|
@ -167,21 +171,20 @@ func (t *Tree) Put(key interface{}, value interface{}) {
|
|
|
|
|
}
|
|
|
|
|
a := (c + 1) / 2
|
|
|
|
|
var fix bool
|
|
|
|
|
fix = put(q, &q.Children[a])
|
|
|
|
|
fix = t.put(key, value, q, &q.Children[a])
|
|
|
|
|
if fix {
|
|
|
|
|
return putFix(int8(c), qp)
|
|
|
|
|
}
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
put(nil, &t.Root)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Remove remove the node from the tree by key.
|
|
|
|
|
// Key should adhere to the comparator's type assertion, otherwise method panics.
|
|
|
|
|
func (t *Tree) Remove(key interface{}) {
|
|
|
|
|
var remove func(**Node) bool
|
|
|
|
|
remove = func(qp **Node) bool {
|
|
|
|
|
t.remove(key, &t.Root)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (t *Tree) remove(key interface{}, qp **Node) bool {
|
|
|
|
|
q := *qp
|
|
|
|
|
if q == nil {
|
|
|
|
|
return false
|
|
|
|
@ -210,16 +213,13 @@ func (t *Tree) Remove(key interface{}) {
|
|
|
|
|
c = 1
|
|
|
|
|
}
|
|
|
|
|
a := (c + 1) / 2
|
|
|
|
|
fix := remove(&q.Children[a])
|
|
|
|
|
fix := t.remove(key, &q.Children[a])
|
|
|
|
|
if fix {
|
|
|
|
|
return removeFix(int8(-c), qp)
|
|
|
|
|
}
|
|
|
|
|
return false
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
remove(&t.Root)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func removeMin(qp **Node, minKey *interface{}, minVal *interface{}) bool {
|
|
|
|
|
q := *qp
|
|
|
|
|
if q.Children[0] == nil {
|
|
|
|
|