Created
August 27, 2021 18:59
-
-
Save r14152/5a0d034ae404a42e9141614bd9b04035 to your computer and use it in GitHub Desktop.
Binary search tree implementation using golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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