binarytree

package module
v1.0.0-...-31d9244 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2025 License: BSD-2-Clause Imports: 6 Imported by: 0

README

go-binarytree

Build Status Go Reference Go Report Card codecov

A simple, generic implementation of Binary Trees in Go.

Example Binary Tree

Installation

Install go-binarytree by executing the following command.

go get -v gopkg.in/dnaeon/go-binarytree.v1

Usage

The following example builds a simple binary tree with 7 nodes, and performs in-, pre-, post- and level-order walking of the tree (error handling is omitted for simplicity).

package main

import (
	"fmt"

	"gopkg.in/dnaeon/go-binarytree.v1"
)

func main() {
	root := binarytree.NewNode(10)
	five := root.InsertLeft(5)
	twenty := root.InsertRight(20)
	five.InsertLeft(9)
	five.InsertRight(18)
	twenty.InsertLeft(3)
	twenty.InsertRight(7)

	fmt.Printf("height of tree: %d\n", root.Height())
	fmt.Printf("size of the tree: %d\n", root.Size())
	fmt.Printf("tree is balanced: %t\n", root.IsBalancedTree())
	fmt.Printf("tree is complete: %t\n", root.IsCompleteTree())
	fmt.Printf("tree is perfect: %t\n", root.IsPerfectTree())

	// Function to be called while walking the tree, which simply
	// prints the values of each visited node
	walkFunc := func(n *binarytree.Node[int]) error {
		fmt.Printf("%d ", n.Value)
		return nil
	}

	fmt.Printf("in-order values: ")
	root.WalkInOrder(walkFunc)
	fmt.Println()

	fmt.Printf("pre-order values: ")
	root.WalkPreOrder(walkFunc)
	fmt.Println()

	fmt.Printf("post-orer values: ")
	root.WalkPostOrder(walkFunc)
	fmt.Println()

	fmt.Printf("level-order values: ")
	root.WalkLevelOrder(walkFunc)
	fmt.Println()
}

Running above example produces the following output.

height of tree: 2
size of the tree: 7
tree is balanced: true
tree is complete: true
tree is perfect: true
in-order values: 9 5 18 10 3 20 7 
pre-order values: 10 5 9 18 20 3 7 
post-orer values: 9 18 5 3 7 20 10 
level-order values: 10 5 20 9 18 3 7 

The following example generates the Dot representation of the binary tree and prints it to the standard output.

package main

import (
	"os"

	"gopkg.in/dnaeon/go-binarytree.v1"
)

func main() {
	root := binarytree.NewNode(10)
	five := root.InsertLeft(5)
	twenty := root.InsertRight(20)
	five.InsertLeft(9)
	five.InsertRight(18)
	twenty.InsertLeft(3)
	twenty.InsertRight(7)

	root.WriteDot(os.Stdout)
}

Running above example produces an output similar to this one.

digraph {
        node [color=lightblue fillcolor=lightblue fontcolor=black shape=record style="filled, rounded"]
        824634441792 [label="<l>|<v> 10|<r>" ]
        824634441792:l -> 824634441856:v
        824634441792:r -> 824634441920:v
        824634441856 [label="<l>|<v> 5|<r>" ]
        824634441856:l -> 824634441984:v
        824634441856:r -> 824634442048:v
        824634441984 [label="<l>|<v> 9|<r>" ]
        824634442048 [label="<l>|<v> 18|<r>" ]
        824634441920 [label="<l>|<v> 20|<r>" ]
        824634441920:l -> 824634442112:v
        824634441920:r -> 824634442176:v
        824634442112 [label="<l>|<v> 3|<r>" ]
        824634442176 [label="<l>|<v> 7|<r>" ]
}

The generated representation can be rendered using graphviz, e.g.

dot -Tsvg /path/to/file.dot -o /tmp/to/file.svg

When building a binary tree with user-defined types such as structs, make sure that you also implement the fmt.Stringer interface for your type, so that Dot generation works properly.

Make sure to check the included test cases for additional examples.

Tests

Run the tests.

make test

License

go-binarytree is Open Source and licensed under the BSD License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IntComparator

func IntComparator(a, b int) int

IntComparator is a comparator function for comparing integer node values.

func StringComparator

func StringComparator(a, b string) int

StringComparator is a comparator function for comparing string node values.

Types

type ComparatorFunc

type ComparatorFunc[T any] func(a, b T) int

ComparatorFunc is a function which compares two values of type T. The comparator function should return:

- A negative integer when A is less than B - A positive integer when A is greater than B - Zero when A equals B

The comparator function is used by IsBinarySearchTree method for validating whether a given binary tree is a Binary Search Tree (BST).

type FindFunc

type FindFunc[T any] func(node *Node[T]) bool

FindFunc is the type of the function predicate which will be invoked for each node while looking for a given node. The function should return true, if the node is the one we are looking for, false otherwise.

type Node

type Node[T any] struct {
	// Value is the value of the node
	Value T
	// Left child of the node
	Left *Node[T]
	// Right child of the node
	Right *Node[T]
	// contains filtered or unexported fields
}

Node represents a node from a binary tree

func NewNode

func NewNode[T any](value T) *Node[T]

NewNode creates a new node

func (*Node[T]) AddAttribute

func (n *Node[T]) AddAttribute(name, value string)

AddAttribute associates an attribute with the node, which will be used when generating the Dot representation of the tree.

func (*Node[T]) AddSkipNodeFunc

func (n *Node[T]) AddSkipNodeFunc(handler SkipNodeFunc[T])

AddSkipNodeFunc adds a new handler for determining whether a node from the tree should be skipped while traversing it.

func (*Node[T]) FindNode

func (n *Node[T]) FindNode(predicate FindFunc[T]) (*Node[T], bool)

Find looks for a node in the tree, which satisfies the given predicate.

func (*Node[T]) GetDotAttributes

func (n *Node[T]) GetDotAttributes() string

GetDotAttributes returns the attributes associated with the node in format suitable for using in the Dot representation.

func (*Node[T]) Height

func (n *Node[T]) Height() int

Height returns the height of the tree

func (*Node[T]) InsertLeft

func (n *Node[T]) InsertLeft(value T) *Node[T]

InsertLeft inserts a new node to the left

func (*Node[T]) InsertRight

func (n *Node[T]) InsertRight(value T) *Node[T]

InsertRight inserts a new node to the right

func (*Node[T]) IsBalancedTree

func (n *Node[T]) IsBalancedTree() bool

IsBalancedTree returns true, if the tree is balanced. A balanced tree is such a tree, for which the height of the left and right sub-trees of each node differ by no more than 1.

func (*Node[T]) IsBinarySearchTree

func (n *Node[T]) IsBinarySearchTree(comparator ComparatorFunc[T]) bool

IsBinarySearchTree returns true, if the tree is a Binary Search Tree (BST).

func (*Node[T]) IsCompleteTree

func (n *Node[T]) IsCompleteTree() bool

IsCompleteTree returns true, if the tree is complete. A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possible.

func (*Node[T]) IsDegenerateTree

func (n *Node[T]) IsDegenerateTree() bool

IsDegenerateTree returns true, if each parent has only one child node.

func (*Node[T]) IsFullNode

func (n *Node[T]) IsFullNode() bool

IsFullNode returns true, if the node contains left and right children

func (*Node[T]) IsFullTree

func (n *Node[T]) IsFullTree() bool

IsFullTree returns true, if the binary tree is full. A full binary tree is a tree in which every node has either 0 or 2 children.

func (*Node[T]) IsLeafNode

func (n *Node[T]) IsLeafNode() bool

IsLeafNode returns true, if the node is a leaf, false otherwise.

func (*Node[T]) IsPerfectTree

func (n *Node[T]) IsPerfectTree() bool

IsPerfectTree returns true, if the binary tree is full and complete

func (*Node[T]) Size

func (n *Node[T]) Size() int

Size returns the size of the tree

func (*Node[T]) WalkInOrder

func (n *Node[T]) WalkInOrder(walkFunc WalkFunc[T]) error

WalkInOrder performs an iterative In-order walking of the binary tree - Left-Node-Right (LNR)

func (*Node[T]) WalkLevelOrder

func (n *Node[T]) WalkLevelOrder(walkFunc WalkFunc[T]) error

WalkLevelOrder performs an iterative Level-order (Breadth-first) walking of the binary tree.

func (*Node[T]) WalkPostOrder

func (n *Node[T]) WalkPostOrder(walkFunc WalkFunc[T]) error

WalkPostOrder performs an iterative Post-order walking of the binary tree - Left-Right-Node (LRN)

func (*Node[T]) WalkPreOrder

func (n *Node[T]) WalkPreOrder(walkFunc WalkFunc[T]) error

WalkPreOrder performs an iterative Pre-order walking of the binary tree - Node-Left-Right (NLR)

func (*Node[T]) WriteDot

func (n *Node[T]) WriteDot(w io.Writer) error

WriteDot generates the Dot representation of the binary tree.

type SkipNodeFunc

type SkipNodeFunc[T any] func(node *Node[T]) bool

SkipNodeFunc is a function which returns true, if the currently being visited node should be skipped.

type WalkFunc

type WalkFunc[T any] func(node *Node[T]) error

WalkFunc is the type of the function which will be invoked while visiting a node from the binary tree.

Jump to

Keyboard shortcuts

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