Skip to content

Instantly share code, notes, and snippets.

@r14152
Created August 27, 2021 18:59
Show Gist options
  • Save r14152/5a0d034ae404a42e9141614bd9b04035 to your computer and use it in GitHub Desktop.
Save r14152/5a0d034ae404a42e9141614bd9b04035 to your computer and use it in GitHub Desktop.
Binary search tree implementation using golang
package main
import "fmt"
type bst struct {
rootValue int
leftNode *bst
rightNode *bst
}
//createNode used to create a node for binary search tree
func createNode(value int) *bst {
return &bst{
rootValue: value,
leftNode: nil,
rightNode: nil,
}
}
func (root *bst) Insert(value int) {
if value < root.rootValue {
if root.leftNode == nil {
root.leftNode = createNode(value)
return
}
root.leftNode.Insert(value)
}
if value > root.rootValue {
if nil == root.rightNode {
root.rightNode = createNode(value)
return
}
root.rightNode.Insert(value)
}
//if its going to equal to root value
//then we are going to ignore that value
//we don't want duplicate value
}
//InOrder print node of tree
func (root *bst) InOrder() {
if nil == root {
return
}
root.leftNode.InOrder()
fmt.Printf("%d ", root.rootValue)
root.rightNode.InOrder()
}
func main() {
numbers := []int{5, 10, 1, 21, 11, 7, 9}
var root *bst
var rootNode bool = true
for _, value := range numbers {
if rootNode {
root = createNode(value)
rootNode = false
}
root.Insert(value)
}
//lets print the tree
root.InOrder()
fmt.Println()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment