Documentation
¶
Overview ¶
Package bstree provides an implementation of the Binary Search Tree (BST) data structure algorithm, where each node has at most two child nodes and the key of its internal node is greater than all the keys in the respective node's left subtree and less than the ones in the right subtree.
Example ¶
bst := New[int, string](func(a, b int) bool { return a < b }) bst.Upsert(10, "foo") bst.Upsert(-1, "baz") bst.Upsert(2, "bar") bst.Upsert(-4, "qux") fmt.Println(bst.Size()) tree := []string{} bst.Traverse(func(item Item[int, string]) { node, _ := bst.Get(item.Key) tree = append(tree, node.Val) }) fmt.Println(tree) for key := range tree { bst.Delete(key) } fmt.Println(bst.Size())
Output: 4 [qux baz bar foo] 0
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrorNotFound = fmt.Errorf("BST node not found")
Functions ¶
This section is empty.
Types ¶
type BsTree ¶
type BsTree[K constraints.Ordered, V any] struct { // contains filtered or unexported fields }
BsTree is the basic component for the BST data structure initialization. It incorporates a thread safe mechanism using `sync.Mutex` to guarantee the data consistency on concurrent read and write operation.
func New ¶
New initializes a new BST data structure together with a comparison operator. Depending on the comparator it sorts the tree in ascending or descending order.
func (*BsTree[K, V]) Get ¶
Get retrieves the node item and an error in case the requested node does not exists.
type Item ¶
type Item[K constraints.Ordered, V any] struct { Key K Val V }
Item contains the node's data as a key-value pair data structure.