Skip to content

Instantly share code, notes, and snippets.

@quintessence
Created January 4, 2014 01:52
Show Gist options
  • Save quintessence/8250446 to your computer and use it in GitHub Desktop.
Save quintessence/8250446 to your computer and use it in GitHub Desktop.
Binary tree practice with Go
package main
import "fmt"
import "strconv"
import "math/rand"
func getOrdinalValue(integerInput int) string {
ordinalValueOfInteger := strconv.Itoa(integerInput)
switch integerInput % 10 {
case 1:
ordinalValueOfInteger += "st"
case 2:
ordinalValueOfInteger += "nd"
case 3:
ordinalValueOfInteger += "rd"
default:
ordinalValueOfInteger += "th"
}
return ordinalValueOfInteger
}
type binaryTree struct {
integerValue int
rightBranch *binaryTree
leftBranch *binaryTree
}
func storeIntegerToBinaryTree(node *binaryTree, integerInput int) *binaryTree{
if node == nil {
return &binaryTree{integerInput, nil, nil}
}
if integerInput <= node.integerValue {
node.leftBranch = storeIntegerToBinaryTree(node.leftBranch, integerInput)
return node
}
node.rightBranch = storeIntegerToBinaryTree(node.rightBranch, integerInput)
return node
}
func main(){
var sizeOfVector int
fmt.Println("How many integers would you like to put into your new binary tree? ")
fmt.Scanf("%d", &sizeOfVector)
vectorWithRandomIntegerElements := make([]int, sizeOfVector)
for i := 0; i < sizeOfVector; i++ {
vectorWithRandomIntegerElements[i] = rand.Intn(500);
var treeNode *binaryTree
treeNode = storeIntegerToBinaryTree(treeNode, vectorWithRandomIntegerElements[i])
fmt.Println("The", getOrdinalValue(i+1), "element is: ",
vectorWithRandomIntegerElements[i])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment