Documentation
¶
Overview ¶
Package tree implements a collection of Generic Tree types including several common Binary Tree types and some N-ary trees.
Index ¶
- Constants
- func BalanceQualityGraph(score float64) string
- func BinaryTreesEqual[T constraints.Ordered](a, b BinaryTree[T]) bool
- func BinaryTreesEquivalent[T constraints.Ordered](a, b BinaryTree[T]) bool
- func Equal[T constraints.Ordered](a, b Tree[T], opts ...OptionFunc) bool
- func Equivalent[T constraints.Ordered](a, b Tree[T], opts ...OptionFunc) bool
- func PrintBinaryTreeASCII[T constraints.Ordered](label string, t BinaryTree[T]) string
- func PrintTreeASCII[T constraints.Ordered](label string, t Tree[T]) string
- func RenderBinaryTree[T constraints.Ordered](t BinaryTree[T], _ int, mode RenderMode) string
- func Split[T constraints.Ordered](t Tree[T], _ T) (Tree[T], Tree[T])
- func ToSlice[T constraints.Ordered](_ Tree[T]) []T
- type AVL
- type BST
- type BalanceQuality
- type BinaryTree
- type OptionFunc
- type Options
- type RedBlack
- type RenderMode
- type Summary
- func (ts *Summary[T]) BalanceQuality() BalanceQuality
- func (ts *Summary[T]) BalanceScore() float64
- func (ts *Summary[T]) HasValues() bool
- func (ts *Summary[T]) Height() int
- func (ts *Summary[T]) HeightEfficiency() float64
- func (ts *Summary[T]) IsEmpty() bool
- func (ts *Summary[T]) MaxValue() (T, bool)
- func (ts *Summary[T]) MinValue() (T, bool)
- func (ts *Summary[T]) NodeCount() int
- func (ts *Summary[T]) OptimalHeight() int
- func (ts *Summary[T]) String() string
- func (ts *Summary[T]) TreeType() string
- type TraverseOrder
- type Traverser
- type Tree
- func Convert[T constraints.Ordered](t Tree[T], opts ...OptionFunc) Tree[T]
- func Join[T constraints.Ordered](a, _ Tree[T], opts ...OptionFunc) (Tree[T], bool)
- func NewAVL[T constraints.Ordered]() Tree[T]
- func NewBST[T constraints.Ordered]() Tree[T]
- func NewRedBlack[T constraints.Ordered]() Tree[T]
- func Prune[T constraints.Ordered](t Tree[T], _ T) Tree[T]
- func Rebalance[T constraints.Ordered](t Tree[T], _ T) Tree[T]
Constants ¶
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 ¶
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]) Delete ¶
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 ¶
Height returns the height of the longest path in the tree from the root node to the farthest leaf.
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]) Delete ¶
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 ¶
Height returns the height of the longest path in the tree from the root node to the farthest leaf.
func (*BST[T]) Insert ¶
Insert inserts the node into the tree, growing as needed, and reports if the operation was successful.
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]) Delete ¶
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 ¶
Height returns the height of the longest path in the tree from the root node to the farthest leaf.
func (*RedBlack[T]) Root ¶
func (t *RedBlack[T]) Root() BinaryTree[T]
Root returns the root node of 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 ¶
BalanceScore returns the numerical balance score (-1.0 to 1.0)
func (*Summary[T]) HeightEfficiency ¶
HeightEfficiency returns the ratio of optimal to actual height
func (*Summary[T]) OptimalHeight ¶
OptimalHeight returns the theoretical minimum height for the node count
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.