How do I implement a binary search tree in Go?

A binary search tree (BST) is a data structure that facilitates fast lookup, addition, and removal of items. A BST has the following properties:

  • Each node has at most two children.
  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.

Below is an example of a binary search tree implementation in Go:

package main import "fmt" type Node struct { Value int Left *Node Right *Node } type BST struct { Root *Node } func (bst *BST) Insert(value int) { bst.Root = insert(bst.Root, value) } func insert(node *Node, value int) *Node { if node == nil { return &Node{Value: value} } if value < node.Value { node.Left = insert(node.Left, value) } else { node.Right = insert(node.Right, value) } return node } func (bst *BST) Search(value int) bool { return search(bst.Root, value) } func search(node *Node, value int) bool { if node == nil { return false } if value == node.Value { return true } if value < node.Value { return search(node.Left, value) } return search(node.Right, value) } func main() { bst := &BST{} bst.Insert(5) bst.Insert(3) bst.Insert(7) bst.Insert(1) bst.Insert(4) fmt.Println(bst.Search(3)) // Output: true fmt.Println(bst.Search(8)) // Output: false }

binary search tree Go data structure algorithm