Skip to content

Instantly share code, notes, and snippets.

@tonyfabeen
Created March 6, 2018 20:53
Show Gist options
  • Save tonyfabeen/a42b47711b3a04e37fd2ab864c46e98e to your computer and use it in GitHub Desktop.
Save tonyfabeen/a42b47711b3a04e37fd2ab864c46e98e to your computer and use it in GitHub Desktop.
BST in golang
package main
import "log"
type Node struct {
Left *Node
Right *Node
Value int
}
type BST struct {
Root *Node
Size int
}
func NewTree() *BST {
return new(BST)
}
func (bst *BST) Insert(element int) {
var node *Node
if bst.Root == nil {
node = &Node{Value: element}
bst.Root = node
bst.Size++
return
}
if element < bst.Root.Value {
bst.Root.Left = bst.insert(element, bst.Root.Left)
} else {
bst.Root.Right = bst.insert(element, bst.Root.Right)
}
}
func (bst *BST) insert(element int, node *Node) *Node {
if node == nil {
bst.Size++
return &Node{Value: element}
}
if element < node.Value {
node.Left = bst.insert(element, node.Left)
} else {
node.Right = bst.insert(element, node.Right)
}
return node
}
func (bst *BST) inorder(node *Node, accumulator []int) []int {
if node == nil {
return accumulator
}
accumulator = bst.inorder(node.Left, accumulator)
log.Printf("%d\n", node.Value)
accumulator = append(accumulator, node.Value)
accumulator = bst.inorder(node.Right, accumulator)
return accumulator
}
func (bst *BST) ToArray() []int {
var accumulator []int
accumulator = bst.inorder(bst.Root, accumulator)
log.Printf("%v\n", accumulator)
return accumulator
}
package main
import "testing"
func TestNewTree(t *testing.T) {
if r := NewTree(); r == nil {
t.Error("not null")
}
}
func TestInsert(t *testing.T) {
nt := NewTree()
nt.Insert(10)
if nt.Root == nil {
t.Error("root should not be null")
}
if nt.Root.Value != 10 {
t.Error("root w/ wrong value")
}
if nt.Size != 1 {
t.Error("should have size 1")
}
nt.Insert(8)
if nt.Root.Left == nil || nt.Root.Left.Value != 8 {
t.Error("should insert value on Left", nt.Root.Left)
}
nt.Insert(11)
if nt.Root.Right == nil || nt.Root.Right.Value != 11 {
t.Error("should insert value on Right", nt.Root.Right)
}
nt.Insert(6)
if nt.Root.Left == nil || nt.Root.Left.Left.Value != 6 {
t.Error("should insert value on Left", nt.Root.Left)
}
if nt.Size != 4 {
t.Error("should have the right size", nt.Size)
}
}
func TestToArray(t *testing.T) {
input := []int{6, 4, 2, 5, 1, 3, 0, 8, 7, 9, 10}
tree := NewTree()
for i := 0; i < len(input); i++ {
tree.Insert(input[i])
}
if tree.Size != len(input) {
t.Error("tree should have the right size")
}
result := tree.ToArray()
for j := 0; j < len(result); j++ {
if j != result[j] {
t.Error("element in wrong order ", j, result[j])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment