RBTree

package module
v0.0.0-...-c7ff165 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 7, 2022 License: Apache-2.0 Imports: 4 Imported by: 0

README

RBTree

Red Black Tree on Golang

Simple realisation of red black tree with simple api.

go get -v github.com/OBrenson/RBTree

Examples of usages

Implementation of Key interface:

type NodeVal int

func (nodeVal NodeVal) Compare(in Key) bool {
	return int(in.(NodeVal)) > int(nodeVal)
}

func (nodeVal NodeVal) String() string {
	return strconv.Itoa(int(nodeVal))
}

func (nodeVal NodeVal) Equal(in Key) bool {
	return int(in.(NodeVal)) == int(nodeVal)
}

Create tree with root node:

tree := CreateTree(NodeVal(0))

Insertion(second param is node`s value, it can be any struct)

err := tree.Insert(NodeVal(rand.Int31n(100)), nil)

Remove:

nfErr := tree.Remove(13) //remove key equal 13

More examples you can find in tree_test.go file.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Key

type Key interface {
	Compare(in Key) bool // in > val -> true
	Equal(in Key) bool   // in == val -> true
	String() string
}

type Node

type Node struct {
	Key Key

	Value interface{}
	// contains filtered or unexported fields
}

Node - standard node of rb tree. All logic is tied up in the keys comparison,

because of this key must realise Key interface and should not be nil.
In Value you can save whatever you want.

type RBTree

type RBTree struct {
	// contains filtered or unexported fields
}

RBTree - Black red tree realisation. All last nodes have black leaves with the nil Key.

Algorithm of insertion has been taken from here https://habr.com/ru/company/otus/blog/472040/
Algorithm of remove has been taken from here https://en.wikipedia.org/wiki/Red–black_tree

func Create

func Create() *RBTree

Create tree without root

func CreateTree

func CreateTree(key Key) *RBTree

Create root of rb tree.

func (*RBTree) Find

func (t *RBTree) Find(key Key) *Node

Find node by its Key

func (*RBTree) GetAll

func (t *RBTree) GetAll() []*Node

Return all nodes of the tree. Does not guarantee the sorted sequence

func (*RBTree) GetSorted

func (t *RBTree) GetSorted() []*Node

Return all nodes of the tree. Guarantee the sorted sequence

func (*RBTree) Insert

func (t *RBTree) Insert(key Key, value interface{}) error

Wrapper for InsertNode. Create new Node from key and value

func (*RBTree) InsertNode

func (t *RBTree) InsertNode(ins *Node) error

Insert new Node in tree. If Node all ready exists Node.Value will be changed

func (*RBTree) PrintTree

func (t *RBTree) PrintTree()

Print tree in a terminal. Very helpful for testing

func (*RBTree) Remove

func (t *RBTree) Remove(key Key) error

Remove node by its Key, if the node is single in the tree, it can`t be removed

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL