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() int func (iterator *Iterator) Value() interface{}
type Node struct { Key interface{} Value interface{} Left *Node Right *Node Parent *Node // contains filtered or unexported fields}
type Tree struct { Root *Node Comparator utils.Comparator // contains filtered or unexported fields}func NewWith(comparator utils.Comparator) *Tree// 实例化一个具有IntComparator的树,即键是int类型的func NewWithIntComparator() *Tree// 用StringComparator实例化一个树,即键的类型是stringfunc NewWithStringComparator() *Tree// 找打大于或等于key节点的最小节点func (tree *Tree) Ceiling(key interface{}) (ceiling *Node, found bool)func (tree *Tree) Clear()func (tree *Tree) Empty() bool// 找打小于或等于key节点的最小节点func (tree *Tree) Floor(key interface{}) (floor *Node, found bool)func (tree *Tree) FromJSON(data []byte) errorfunc (tree *Tree) Get(key interface{}) (value interface{}, found bool)func (tree *Tree) Iterator() Iteratorfunc (tree *Tree) Keys() []interface{}func (tree *Tree) Left() *Nodefunc (tree *Tree) Put(key interface{}, value interface{})func (tree *Tree) Remove(key interface{})func (tree *Tree) Right() *Nodefunc (tree *Tree) Size() intfunc (tree *Tree) String() stringfunc (tree *Tree) ToJSON() ([]byte, error)func (tree *Tree) Values() []interface{}
例子:
package mainimport ( "fmt" rbt "github.com/emirpasic/gods/trees/redblacktree")// RedBlackTreeExample to demonstrate basic usage of RedBlackTreefunc main() { tree := rbt.NewWithIntComparator() // empty(keys are of type int) tree.Put(1, "x") // 1->x tree.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) // // RedBlackTree // │ ┌── 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) // // RedBlackTree // │ ┌── 6 // │ ┌── 5 // └── 4 // │ ┌── 3 // └── 1 tree.Clear() // empty tree.Empty() // true tree.Size() // 0}