Skip to content

Instantly share code, notes, and snippets.

@dantheman213

dantheman213/bst.go

Created Apr 21, 2020
Embed
What would you like to do?
Golang binary tree
package main
import "fmt"
type Node struct {
Left, Right *Node
Value int64
}
type BinarySearchTree struct {
Root *Node
}
func NewBinarySearchTree(rootValue int64) *BinarySearchTree {
tree := &BinarySearchTree{}
tree.Insert(tree.Root, rootValue)
return tree
}
func (t *BinarySearchTree) Insert(n *Node, value int64) {
if n == nil {
fmt.Printf("Inserted value: %d\n", value)
n = &Node{
Value: value,
}
} else {
if value < n.Value {
t.Insert(n.Left, value)
} else if value > n.Value {
t.Insert(n.Right, value)
}
}
}
func (t *BinarySearchTree) ListAll(n *Node) {
if n != nil {
fmt.Printf("Value: %d\n", n.Value)
t.ListAll(n.Left)
t.ListAll(n.Right)
}
}
func main() {
fmt.Println("Hello World")
tree := NewBinarySearchTree(500)
tree.Insert(tree.Root, 350)
tree.Insert(tree.Root, 865)
tree.Insert(tree.Root, 251)
tree.Insert(tree.Root, 201)
tree.Insert(tree.Root, 101)
tree.Insert(tree.Root, 59)
tree.Insert(tree.Root, 20)
tree.Insert(tree.Root, 958)
tree.Insert(tree.Root, 632)
tree.Insert(tree.Root, 590)
tree.Insert(tree.Root, 1001)
tree.Insert(tree.Root, 999)
tree.ListAll(tree.Root)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.