A generic binary search tree (BST) can be implemented in Go using Go's type parameters introduced in version 1.18. Below is an example of a generic binary search tree that supports inserting and searching for values.
package main
import (
"fmt"
)
// Node represents a node in the binary search tree
type Node[T comparable] struct {
value T
left *Node[T]
right *Node[T]
}
// BST represents the binary search tree
type BST[T comparable] struct {
root *Node[T]
}
// Insert adds a value to the BST
func (b *BST[T]) Insert(value T) {
b.root = insert(b.root, value)
}
func insert[T comparable](node *Node[T], value T) *Node[T] {
if node == nil {
return &Node[T]{value: value}
}
if value < node.value {
node.left = insert(node.left, value)
} else {
node.right = insert(node.right, value)
}
return node
}
// Search checks if a value exists in the BST
func (b *BST[T]) Search(value T) bool {
return search(b.root, value)
}
func search[T comparable](node *Node[T], value T) bool {
if node == nil {
return false
}
if value == node.value {
return true
} else if value < node.value {
return search(node.left, value)
} else {
return search(node.right, value)
}
}
func main() {
tree := &BST[int]{}
tree.Insert(5)
tree.Insert(3)
tree.Insert(7)
fmt.Println(tree.Search(3)) // true
fmt.Println(tree.Search(6)) // false
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?