tree

package
v0.0.0-...-8f1ea74 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2025 License: Apache-2.0 Imports: 8 Imported by: 0

README

Go Tree Data Structures

This package contains a variety of common ordered, rooted tree types implemented in Go using generics. It supports all types that satisfy constraints.Ordered, including integers, floating-point numbers, and strings.

There are implementations of a number of traditional Binary Trees (Binary Search Tree, AVL Tree, Red/Black tree, etc.) as well as future updates to include some N-ary (multiple values per node) trees like B-tree and B+-tree.

More complex or esoteric tree types are currently not in scope for this package.

The package contains comprehensive unit tests as well as a suite of Benchmarks that can be used to compare and contrast the various trees performances.

This implementation is not focused on ultimate performance, but rather on letting me work towards simplicity, readability, and ease of use.

Currently Implemented Tree Types

Binary Trees
Binary Search Tree (BST)

Simplest of all binary trees, a node, two children, no balancing. Simple insert/delete/search operations.

Adelson Velsky and Landis (AVL) Tree

A self-balancing binary tree where the height of any two child subtrees differs by no more than 1. Rebalancing happens automatically during insert and delete operations if the resulting tree is unbalanced.

Red-Black Tree

Approximately balanced binary tree with red/black node coloring that offers a good balance between insertion performance and search performance.

N-ary Tree Types

In graph theory, an n-ary tree (for nonnegative integers n) is an ordered tree in which each node has no more than n children.

B-Tree

A B-tree is a self-balancing tree data structure that maintains sorted data and allows searches, sequential access, insertions, and deletions in logarithmic time.

B+-Tree

A B+ tree can be viewed as a B-tree in which each node contains only keys (not key–value pairs), and to which an additional level is added at the bottom with linked leaves.

Core Interfaces

Tree Interface

All tree types implement the Tree[T] interface:

type Tree[T constraints.Ordered] interface {
    Insert(v T) bool        // Insert a value
    Delete(v T) bool        // Delete a value
    Search(v T) bool        // Search for a value
    Height() int            // Get tree height
    Clone[T]() Tree[T]      // Create a deep copy
    Traverse(order TraverseOrder) <-chan T  // Traverse tree
}
BinaryTree Interface

Binary tree nodes implement the BinaryTree[T] interface:

type BinaryTree[T constraints.Ordered] interface {
    Tree[T]
    HasLeft() bool          // Check if left child exists
    HasRight() bool         // Check if right child exists
    Left() BinaryTree[T]    // Get left child
    Right() BinaryTree[T]   // Get right child
    Value() T               // Get node value
    Metadata() string       // Reports node-specific metadata
}

Tree Utility Functions

The package provides some utility functions for tree operations:

  • Equal[T](a, b Tree[T]) bool: Reports if two trees have the same values AND the same structure regardless of underlying type. (e.g., A balanced AVL tree and a balanced BST would be considered Equal if they have the same values and structure.)
  • Equivalent[T](a, b Tree[T]) bool: Reports if the two trees have the same values in the same order but ignoring tree structure. (So a one-legged BST and and AVL could have be equivalent, but not Equal. Similarly, a B-Tree and a BST could be Equivalent but won't have the same structure.)

Traversal Orders

The package supports multiple tree traversal methods:

type TraverseOrder int
const (
    TraverseInOrder         // Left, Root, Right
    TraversePreOrder        // Root, Left, Right
    TraversePostOrder       // Left, Right, Root
    TraverseReverseOrder    // Right, Root, Left
    TraverseLevelOrder      // Breadth-first in order traversal
)

The Traverse method uses a <-chan T to return the values in the specified order. The channel is closed when the traversal is complete.

Visualization

ASCII Tree Display

Use PrintBinaryTreeASCII to visualize tree structure:

tree := NewAVL[int]()
tree.Insert(10)
tree.Insert(5)
tree.Insert(15)
tree.Insert(12)

fmt.Println(PrintBinaryTreeASCII("My First AVL Tree", tree.Root()))

Output:

My First AVL Tree

     10
     (0)
     / \
    5   15
  (0)   (-1)
        /
       12
       (0)

Usage Examples

Basic Usage
// Create an AVL tree for integers
tree := NewAVL[int]()

// Insert values
tree.Insert(10)
tree.Insert(5)
tree.Insert(15)
tree.Insert(3)
tree.Insert(7)

// Search for values
found := tree.Search(7)  // returns true
missing := tree.Search(12)  // returns false

// Delete values
deleted := tree.Delete(5)  // returns true

// Get tree height
height := tree.Height()  // returns height of tallest leg of the tree
Tree Traversal
// Traverse tree in different orders
for value := range tree.Traverse(TraverseInOrder) {
    fmt.Printf("%d ", value)
}
// Output: 3 7 10 15 

for value := range tree.Traverse(TraverseLevelOrder) {
    fmt.Printf("%d ", value)
}
// Output: 10 7 15 3
Working with Different Types
// String tree
stringTree := NewBST[string]()
stringTree.Insert("apple")
stringTree.Insert("banana")
stringTree.Insert("cherry")

// Float tree
floatTree := NewAVL[float64]()
floatTree.Insert(3.14)
floatTree.Insert(2.71)
floatTree.Insert(1.41)

Tests

The package includes comprehensive test coverage across multiple test files.

Running Tests
# Run all tests
go test ./tree

# Run tests with verbose output
go test -v ./tree

# Run specific test
go test -run TestAVLInsert ./tree

# Run tests with race detection
go test -race ./tree

# Run tests with coverage
go test -cover ./tree
Test Coverage

The test suite covers:

  • Basic tree operations (insert, delete, search)
  • Tree balancing and rotations (AVL-specific)
  • Edge cases (empty trees, single nodes, duplicate values)
  • Tree traversal in all supported orders
  • Tree comparison and equality functions
  • ASCII visualization output
  • Error handling and boundary conditions

Benchmarks

The package includes performance benchmarks to compare different tree implementations.

Running Benchmarks
# Run all benchmarks
go test -bench=. ./tree

# Run specific benchmark
go test -bench=BenchmarkTreeInsert ./tree

# Run benchmarks with memory stats
go test -bench=. -benchmem ./tree

# Run benchmarks multiple times for accuracy
go test -bench=BenchmarkTreeInsert -count=5 ./tree

# Filter benchmarks by tree type
go test -bench=. -args -tree-type=AVL ./tree

# Limit benchmark dataset size
go test -bench=. -args -tree-size-limit=10000 ./tree
Benchmark Flags

The benchmarks support several command-line flags:

  • -tree-type: Filter benchmarks by tree type (BST, AVL)
  • -tree-size-limit: Set maximum number of nodes to insert in a tree for testing
  • -count: Number of times to run the benchmarks
Example Benchmark Output
BenchmarkTreeInsert/BST-0000100-8         50000    25432 ns/op    1024 B/op     12 allocs/op
BenchmarkTreeInsert/AVL-0000100-8         45000    28901 ns/op    1024 B/op     12 allocs/op
BenchmarkTreeInsert/BST-0001000-8          5000   245821 ns/op   10240 B/op    120 allocs/op
BenchmarkTreeInsert/AVL-0001000-8          4800   251234 ns/op   10240 B/op    120 allocs/op

Future Plans

N-ary Tree Types (Planned)
  • B-Tree: Self-balancing tree for systems with large branching factors
  • B+-Tree: B-tree variant optimized for range queries and sequential access
Additional Expected Features (Planned)
  • Tree persistence and serialization
  • More comprehensive tree utility functions
  • Performance optimizations
  • Thread-safe checks and variants
  • Custom comparison function support
Longer term / lower priority features
  • Interactive Tree builder taking advantage of the existing methods and rendering capabilities (e.g. Insert, Delete, Search displaying the updated tree after each action)
  • Dynamic tree width allocation based on actual tree structure bushy-ness. Right now a 5 level deep tree with 5 digit wide node values ends up being > 160 characters wide regardless of how many nodes are present and where they fall in the overall tree.

Development

Contributing

When adding new tree types or features:

  1. Implement the Tree[T] interface
  2. Implement the more specific type of Tree interface (BinaryTree[T] or NAryTree[T])
  3. Add comprehensive unit tests covering normal expected values, nil and edge cases, as well as any exceptions that could occur.
  4. Include benchmarks comparing with existing implementations
  5. Update documentation and examples
  6. Ensure all tests pass with go test ./...
  7. Verify no lint issues with golangci-lint run ./...

Documentation

Overview

Package tree implements a collection of Generic Tree types including several common Binary Tree types and some N-ary trees.

Index

Constants

View Source
const MaxPrintableLevel = 6 // 0-based, so 6 means 7 levels of tree height (0-6)

MaxPrintableLevel is the maximum number of levels to print because the ASCII tree is approximately doubling in printed width at each level.

This value is arbitrary.

But using the general printing spacings for a node width of various chars, we end up with a potential max width for depth N as follows.

depth | width=3 | width=5 | width=7 ------+---------+---------+--------- 1 | 3 | 5 | 7 2 | 12 | 13 | 24 3 | 26 | 33 | 50 4 | 54 | 73 | 102 5 | 110 | 158 | 206 6 | 222 | 318 | 414 7 | 443 | 638 | 822 8 | 894 | 1278 | 1662 9 | 1790 | 2558 | 3326

Variables

This section is empty.

Functions

func BalanceQualityGraph

func BalanceQualityGraph(score float64) string

BalanceQualityGraph returns a string representation of the balance quality as an short ASCII art horizontal graph with label.

func BinaryTreesEqual

func BinaryTreesEqual[T constraints.Ordered](a, b BinaryTree[T]) bool

BinaryTreesEqual tests if two BinaryTrees have the same structure and values.

TODO(rsned): Make this public method?

func BinaryTreesEquivalent

func BinaryTreesEquivalent[T constraints.Ordered](a, b BinaryTree[T]) bool

BinaryTreesEquivalent tests if two BinaryTrees have the same values in the same order.

As an initial pass, we start with step by step walking to see if they are the same.

func Equal

func Equal[T constraints.Ordered](a, b Tree[T], opts ...OptionFunc) bool

Equal reports if the two trees containt the same nodes in the same structure.

It is possible for two different types of Binary Trees, for example, to have the same nodes and the same structure.

e.g., Tree A, a BST:

  5
 / \
2   8

and Tree B, an AVL tree:

  5
 / \
2   8

Are equal because the trees have the same nodes and structure.

Whereas if Tree A was:

    8
   /
  5
 /
2

It would be equivalent, but not equal, because it has the same node values in an In-Order traversal, but the structure is different.

This function supports changing the tolerance for floating point comparisons.

func Equivalent

func Equivalent[T constraints.Ordered](a, b Tree[T], opts ...OptionFunc) bool

Equivalent reports if the two trees have the same node values in the same order. This is essentially reporting if the two trees have the same In-Order traversal outputs, but not caring about the underlying structure or implementation.

See the description for Equal for some examples of this.

e.g., Tree A, a BST:

	    8
       / \
	  5  15
     /  /  \
    2  13  17

and Tree B, a B-Tree

	      13
         /  \
	2|5|8    15|17

are equivalent because they have the same node values in the same order.

This function supports changing the tolerance for floating point comparisons.

func PrintBinaryTreeASCII

func PrintBinaryTreeASCII[T constraints.Ordered](label string, t BinaryTree[T]) string

PrintBinaryTreeASCII outputs the binary tree up to 6 levels deep for the purpose of aiding in testing and debugging.

This method takes a binary tree of type T with an explicit assumption the values in the tree are under 11 character wide when formatted and printed. e.g. -21, 123, 7, 6.02e23, etc. Values wider than 11 characters may work fine, but no testing or quality checks have been done.

An optional label is output before the tree contents with a blank line separator between the label and the tree.

TODO(rsned): Add an elideLevel int param to do the eliding dynamically.

func PrintTreeASCII

func PrintTreeASCII[T constraints.Ordered](label string, t Tree[T]) string

PrintTreeASCII outputs the Tree up to a reasonable number of levels deep for the purpose of aiding in testing and debugging.

This method takes a Tree[T] with an explicit assumption the values in the tree are under a predefined width when formatted and printed. e.g. -21, 123, 7, 6.02e23, "Yellow", etc. Values wider than the cutoff may work fine, but no testing or quality checks have been done.

An optional label is output before the tree contents with a blank line separator between the label and the tree.

TODO(rsned): Add an elideLevel int param to do the eliding dynamically.

func RenderBinaryTree

func RenderBinaryTree[T constraints.Ordered](t BinaryTree[T], _ int, mode RenderMode) string

RenderBinaryTree returns the given tree in the given mode rendered into string form.

func Split

func Split[T constraints.Ordered](t Tree[T], _ T) (Tree[T], Tree[T])

Split splits the Tree into two trees such that first tree returned constains the values up to and including the split point, and the second tree the remainder. The output Trees will be of the same underlying type as the input.

If the value falls between two nodes in the tree, then tree one will end at the value closest without exceeding the given value.

The resulting Trees are NOT guaranteed to be balanced or optimal.

Your right to be foolish is supported. For example splitting on a value outside the trees limits will give back the original tree and a nil tree.

func ToSlice

func ToSlice[T constraints.Ordered](_ Tree[T]) []T

ToSlice converts the tree to a slice in natural order.

Types

type AVL

type AVL[T constraints.Ordered] struct {
	// contains filtered or unexported fields
}

AVL tree (named after inventors Adelson-Velsky and Landis) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property.

func (*AVL[T]) Clone

func (t *AVL[T]) Clone() Tree[T]

Clone creates a deep copy of the AVL tree.

func (*AVL[T]) Delete

func (t *AVL[T]) Delete(_ T) bool

Delete the requested node from the tree and reports if it was successful. If the value is not in the tree, the tree is unchanged and false is returned. If the node is not a leaf the trees internal structure may be updated.

func (*AVL[T]) Height

func (t *AVL[T]) Height() int

Height returns the height of the longest path in the tree from the root node to the farthest leaf.

func (*AVL[T]) Insert

func (t *AVL[T]) Insert(v T) bool

Insert inserts the node into the tree, growing as needed.

func (*AVL[T]) Root

func (t *AVL[T]) Root() BinaryTree[T]

Root returns the root node of the tree.

func (*AVL[T]) Search

func (t *AVL[T]) Search(v T) bool

Search reports if the given value is in the tree.

func (*AVL[T]) Traverse

func (t *AVL[T]) Traverse(tOrder TraverseOrder) <-chan T

Traverse traverse the tree in the specified order emitting the values to the channel. Channel is closed once the final value is emitted.

type BST

type BST[T constraints.Ordered] struct {
	// contains filtered or unexported fields
}

BST is the simplest binary tree type. A node value and left and right pointers. No balancing or shuffling.

func (*BST[T]) Clone

func (t *BST[T]) Clone() Tree[T]

Clone creates a deep copy of the BST tree.

func (*BST[T]) Delete

func (t *BST[T]) Delete(v T) bool

Delete the requested node from the tree and reports if it was successful. If the value is not in the tree, the tree is unchanged and false is returned. If the node is not a leaf the trees internal structure may be updated.

func (*BST[T]) Height

func (t *BST[T]) Height() int

Height returns the height of the longest path in the tree from the root node to the farthest leaf.

func (*BST[T]) Insert

func (t *BST[T]) Insert(v T) bool

Insert inserts the node into the tree, growing as needed, and reports if the operation was successful.

func (*BST[T]) Root

func (t *BST[T]) Root() BinaryTree[T]

Root returns the root node of the tree.

func (*BST[T]) Search

func (t *BST[T]) Search(v T) bool

Search reports if the given value is in the tree.

func (*BST[T]) Traverse

func (t *BST[T]) Traverse(tOrder TraverseOrder) <-chan T

Walk traverse the tree in the specified order emitting the values to the channel. Channel is closed once the final value is emitted.

type BalanceQuality

type BalanceQuality int

BalanceQuality is a enum for the balance quality of a tree. It is an arbitrary set of values ranging from Well Balanced to Severely Right/Left Heavy, to Degenerate. The change over points are chosen by me to what feels reasonable.

const (
	BalanceUnknown BalanceQuality = iota
	DegenerateLeft                // Essentially a linked list
	SeverelyLeftHeavy
	ModeratelyLeftHeavy
	SlightlyLeftHeavy
	WellBalanced
	SlightlyRightHeavy
	ModeratelyRightHeavy
	SeverelyRightHeavy
	DegenerateRight // Essentially a linked list
)

func (BalanceQuality) String

func (bq BalanceQuality) String() string

balanceQualityString converts BalanceQuality enum to string

type BinaryTree

type BinaryTree[T constraints.Ordered] interface {
	Tree[T]

	// Value returns the value at this node in the tree.
	Value() T

	// HasLeft reports if this node has a Left child.
	HasLeft() bool

	// HasRight reports if this node has a Right child.
	HasRight() bool

	// Left returns the Left child, if any, of this node.
	Left() BinaryTree[T]

	// Right returns the Right child, if any, of this node.
	Right() BinaryTree[T]

	// Metadata returns a metadata string, if any, for this node in the tree.
	//
	// Some examples include Balance Factor for an AVL tree, or Red/Black for a
	// node in a Red-Black tree.
	//
	// This is primarily used when rendering the tree.
	Metadata() string
}

BinaryTree is the simplest tree type.

A node value and two children (left and right).

type OptionFunc

type OptionFunc func(c *Options)

treeOptionFunc is a function to set options for use in variadic opt params.

func FloatingPointTolerance

func FloatingPointTolerance(tol float64) OptionFunc

FloatingPointTolerance sets the tolerance when compariong Floating Point values in tree operations.

func IgnoreDuplicates

func IgnoreDuplicates(ignore bool) OptionFunc

IgnoreDuplicates tells the tree function that a duplicate value in an operation should be ignored. (Such as when joining two Trees)

type Options

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

Options contains the various settings used in these tree functions.

type RedBlack

type RedBlack[T constraints.Ordered] struct {
	// contains filtered or unexported fields
}

RedBlack Tree is a binary search tree where each node has an additional attribute: a color, which can be either red or black. By maintaining specific coloring rules during insertions and deletions, the tree ensures it stays approximately balanced.

The Five Rules Every Red-Black tree must satisfy these properties:

  • Every node is colored either red or black
  • The root node is always black
  • All leaf nodes (nil children nodes) are black
  • Red nodes cannot have red children (no two red nodes can be adjacent)
  • Every path from a node to its descendant nil nodes contains the same number of black nodes (this is called the black-height property)

The longest possible path from root to leaf can be at most twice as long as the shortest path, which happens when one path alternates red-black nodes while another has only black nodes.

func (*RedBlack[T]) Clone

func (t *RedBlack[T]) Clone() Tree[T]

Clone creates a deep copy of the Red-Black tree.

func (*RedBlack[T]) Delete

func (t *RedBlack[T]) Delete(v T) bool

Delete the requested node from the tree and reports if it was successful. If the value is not in the tree, the tree is unchanged and false is returned.

The trees internal structure may be updated.

func (*RedBlack[T]) Height

func (t *RedBlack[T]) Height() int

Height returns the height of the longest path in the tree from the root node to the farthest leaf.

func (*RedBlack[T]) Insert

func (t *RedBlack[T]) Insert(v T) bool

Insert inserts the node into the tree, growing as needed.

func (*RedBlack[T]) Root

func (t *RedBlack[T]) Root() BinaryTree[T]

Root returns the root node of the tree.

func (*RedBlack[T]) Search

func (t *RedBlack[T]) Search(v T) bool

Search reports if the given value is in the tree.

func (*RedBlack[T]) Traverse

func (t *RedBlack[T]) Traverse(tOrder TraverseOrder) <-chan T

Traverse traverse the tree in the specified order emitting the values to the channel. Channel is closed once the final value is emitted.

type RenderMode

type RenderMode int

RenderMode is an enum for output formats when printing out trees.

const (
	ModeASCII RenderMode = iota // Also the default value.
	ModeSVG
)

Set of current render modes.

type Summary

type Summary[T constraints.Ordered] struct {
	// contains filtered or unexported fields
}

Summary contains comprehensive statistics and analysis of a Tree's data structure to help understand its characteristics at a glance.

func Summarize

func Summarize[T constraints.Ordered](tree Tree[T]) *Summary[T]

Summarize takes a tree and returns comprehensive statistics and analysis about the tree structure, balance, performance characteristics, and more.

func (*Summary[T]) BalanceQuality

func (ts *Summary[T]) BalanceQuality() BalanceQuality

BalanceQuality returns the balance quality enum

func (*Summary[T]) BalanceScore

func (ts *Summary[T]) BalanceScore() float64

BalanceScore returns the numerical balance score (-1.0 to 1.0)

func (*Summary[T]) HasValues

func (ts *Summary[T]) HasValues() bool

HasValues returns whether the tree contains values

func (*Summary[T]) Height

func (ts *Summary[T]) Height() int

Height returns the maximum depth from root to leaf

func (*Summary[T]) HeightEfficiency

func (ts *Summary[T]) HeightEfficiency() float64

HeightEfficiency returns the ratio of optimal to actual height

func (*Summary[T]) IsEmpty

func (ts *Summary[T]) IsEmpty() bool

IsEmpty returns whether the tree has any nodes

func (*Summary[T]) MaxValue

func (ts *Summary[T]) MaxValue() (T, bool)

MaxValue returns the maximum value in the tree

func (*Summary[T]) MinValue

func (ts *Summary[T]) MinValue() (T, bool)

MinValue returns the minimum value in the tree

func (*Summary[T]) NodeCount

func (ts *Summary[T]) NodeCount() int

NodeCount returns the total number of nodes in the tree

func (*Summary[T]) OptimalHeight

func (ts *Summary[T]) OptimalHeight() int

OptimalHeight returns the theoretical minimum height for the node count

func (*Summary[T]) String

func (ts *Summary[T]) String() string

String returns a human-readable representation of the tree summary

func (*Summary[T]) TreeType

func (ts *Summary[T]) TreeType() string

TreeType returns the type of tree (BST, AVL, RedBlack, etc.)

type TraverseOrder

type TraverseOrder int

TraverseOrder represents the common orders that tree nodes may be traversed in.

const (
	// TraverseInOrder traverses from the left subtree to the root then to the right subtree.
	TraverseInOrder TraverseOrder = iota
	// TraversePreOrder traverses from the root to the left subtree then to the right subtree.
	TraversePreOrder
	// TraversePostOrder traverses from the left subtree to the right subtree then to the root.
	TraversePostOrder

	// TraverseReverseOrder traverses from the right subtree to the root then to the left.
	TraverseReverseOrder

	// TraverseLevelOrder performs breadth first search where nodes are visited by level
	// left to right before moving to the next level down.
	TraverseLevelOrder
)

func (TraverseOrder) String

func (t TraverseOrder) String() string

String returns a string label for the TraverseOrder type.

type Traverser

type Traverser[T constraints.Ordered] interface {
	// Traverse traverse the tree in the specified order emitting the values to
	// the channel. Channel is closed once the final value is emitted.
	Traverse(order TraverseOrder) <-chan T
}

Traverser is an interface for trees that implement a way to traverse themselves.

type Tree

type Tree[T constraints.Ordered] interface {
	// Insert adds the given value into the true.
	// If the value could not be added, false is returned.
	Insert(v T) bool

	// Delete the requested node from the tree and reports if it was successful.
	// If the value is not in the tree, the tree is unchanged and false
	// is returned.
	//
	// If the node is not a leaf the trees internal structure may be updated.
	Delete(v T) bool

	// Search reports if the given value is in the tree.
	Search(v T) bool

	// Height returns the height of the longest path in the tree from the
	// root node to the farthest leaf.
	Height() int

	// Clone creates a deep copy of the tree and returns it.
	Clone() Tree[T]

	Traverser[T]
}

Tree defines the basic interface common to all trees.

func Convert

func Convert[T constraints.Ordered](t Tree[T], opts ...OptionFunc) Tree[T]

Convert attempts to convert the given tree into a tree of a type specified in the options. For example, Convert a BST to an AVL tree.

More discourse will follow on how different combinations of options will be handled such as specifying multiple tree types, etc.

opts: Underlying type

func Join

func Join[T constraints.Ordered](a, _ Tree[T], opts ...OptionFunc) (Tree[T], bool)

Join attempts to merge the given trees following the given options (if any). If the joining was unsuccessful for any reason, the resulting Tree should not be used, and false will be returned.

Options can include things like what strategy to use when encountering duplicate values, hints or requirements on type of output tree, etc.

func NewAVL

func NewAVL[T constraints.Ordered]() Tree[T]

NewAVL returns an empty AVL tree ready to use.

func NewBST

func NewBST[T constraints.Ordered]() Tree[T]

NewBST returns an empty BST tree ready to use.

func NewRedBlack

func NewRedBlack[T constraints.Ordered]() Tree[T]

NewRedBlack returns an empty Red-Black tree ready to use.

func Prune

func Prune[T constraints.Ordered](t Tree[T], _ T) Tree[T]

Prune removes the whole subtree that is homed at val.

Your right to be foolish is supported. For example pruning on the root value will give back an empty tree.

func Rebalance

func Rebalance[T constraints.Ordered](t Tree[T], _ T) Tree[T]

Rebalance attempts to perform some after-market rebalancing on a tree.

For types that normally include some type of balancing, they may short-circuit this call.

Jump to

Keyboard shortcuts

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