Skip to content

Instantly share code, notes, and snippets.

@lkrych
Created August 11, 2018 18:45
Show Gist options
  • Save lkrych/6c0d5dea6edd288e487f69ecb590f6ee to your computer and use it in GitHub Desktop.
Save lkrych/6c0d5dea6edd288e487f69ecb590f6ee to your computer and use it in GitHub Desktop.
Binary Search tree implementation in go
//A binary search tree has reference to its node
type BSTree struct {
root *Node
}
func (btree *BSTree) isEmpty() bool {
return btree.root == nil
}
//search for the key recursively
func get(x *Node, key string) *Node {
if x == nil {
return nil
}
if x.key > key {
return get(x.left, key)
} else if x.key < key {
return get(x.right, key)
} else {
//x.key must equal key
return x
}
}
//update a key, or insert a new node into tree
func put(x *Node, key string, value int) *Node {
if x == nil {
//we've reached a nil left or right subtree.
return &Node{
key: key,
val: value,
}
}
if x.key > key {
x.left = put(x.left, key, value)
} else if x.key < key {
x.right = put(x.right, key, value)
} else {
//if the key already exists in the tree, update it
x.val = value
}
return x
}
func returnKeys(x *Node) []Node {
ordered := []Node{}
if x == nil {
return ordered
}
//in-order traversal
ordered = append(ordered, returnKeys(x.left)...)
ordered = append(ordered, *x)
ordered = append(ordered, returnKeys(x.right)...)
return ordered
}
type Node struct {
key string
val int
left *Node
right *Node
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment