AVL平衡二叉树
type Iterator
func (iterator *Iterator) Begin() // 将迭代器重置为初始状态,然后调用Next获取第一个元素func (iterator *Iterator) End() // 将迭代器移过最后一个元素,然后调用Prev获取最后一个元素// 将迭代器移动到第一个元素,如果容器中有第一个元素则返回true。// 如果First()返回true,则可以通过index()和value()检索第一个元素的索引和值。修改迭代器的状态func (iterator *Iterator) First() bool// 将迭代器移动到最后元素,如果容器中有第一个元素则返回true。// 如果Last()返回true,则可以通过index()和value()检索第一个元素的索引和值。修改迭代器的状态func (iterator *Iterator) Last() boolfunc (iterator *Iterator) Next() boolfunc (iterator *Iterator) Prev() boolfunc (iterator *Iterator) Index() intfunc (iterator *Iterator) Value() interface{}
type Node
type Node struct {Key interface{}Value interface{}Parent *Node // Parent nodeChildren [2]*Node // Children nodes// contains filtered or unexported fields}func (n *Node) Next() *Nodefunc (n *Node) Prev() *Nodefunc (n *Node) String() string
type Tree
func NewWith(comparator utils.Comparator) *Tree// 实例化一个具有IntComparator的树,即键是int类型的func NewWithIntComparator() *Tree// 用StringComparator实例化一个树,即键的类型是stringfunc NewWithStringComparator() *Tree// 找打大于或等于key节点的最小节点func (t *Tree) Ceiling(key interface{}) (floor *Node, found bool)func (t *Tree) Clear()func (t *Tree) Empty() bool// 找打小于或等于key节点的最小节点func (t *Tree) Floor(key interface{}) (floor *Node, found bool)func (tree *Tree) FromJSON(data []byte) errorfunc (t *Tree) Get(key interface{}) (value interface{}, found bool)// 返回一个有序迭代器func (tree *Tree) Iterator() containers.ReverseIteratorWithKeyfunc (t *Tree) Keys() []interface{}func (t *Tree) Left() *Nodefunc (t *Tree) Put(key interface{}, value interface{})func (t *Tree) Remove(key interface{})func (t *Tree) Right() *Nodefunc (t *Tree) Size() intfunc (t *Tree) String() stringfunc (tree *Tree) ToJSON() ([]byte, error)func (t *Tree) Values() []interface{}
例子:
package mainimport ("fmt"avl "github.com/emirpasic/gods/trees/avltree")// AVLTreeExample to demonstrate basic usage of AVLTreefunc main() {tree := avl.NewWithIntComparator() // empty(keys are of type int)tree.Put(1, "x") // 1->xtree.Put(2, "b") // 1->x, 2->b (in order)tree.Put(1, "a") // 1->a, 2->b (in order, replacement)tree.Put(3, "c") // 1->a, 2->b, 3->c (in order)tree.Put(4, "d") // 1->a, 2->b, 3->c, 4->d (in order)tree.Put(5, "e") // 1->a, 2->b, 3->c, 4->d, 5->e (in order)tree.Put(6, "f") // 1->a, 2->b, 3->c, 4->d, 5->e, 6->f (in order)fmt.Println(tree)//// AVLTree// │ ┌── 6// │ ┌── 5// └── 4// │ ┌── 3// └── 2// └── 1_ = tree.Values() // []interface {}{"a", "b", "c", "d", "e", "f"} (in order)_ = tree.Keys() // []interface {}{1, 2, 3, 4, 5, 6} (in order)tree.Remove(2) // 1->a, 3->c, 4->d, 5->e, 6->f (in order)fmt.Println(tree)//// AVLTree// │ ┌── 6// │ ┌── 5// └── 4// └── 3// └── 1tree.Clear() // emptytree.Empty() // truetree.Size() // 0}
