noodling on The Practice Of Programming, Chapter 2

This commit is contained in:
David 2021-07-25 19:29:13 -04:00
commit 7aece75825
3 changed files with 100 additions and 0 deletions

72
datastructures.go Normal file
View File

@ -0,0 +1,72 @@
package main
type TreeNode interface {
Left() TreeNode
Right() TreeNode
}
type BTreeNode struct {
left TreeNode
right TreeNode
}
type StringyBTreeNode struct {
k string
v interface{}
BTreeNode
}
func NewStringyBTree(k string, v interface{}) *StringyBTreeNode {
return &StringyBTreeNode{
k: k,
v: v,
}
}
func (sbt *StringyBTreeNode) Left() TreeNode {
return sbt.left
}
func (sbt *StringyBTreeNode) Right() TreeNode {
return sbt.right
}
func (sbt *StringyBTreeNode) Insert(k string, v interface{}) *StringyBTreeNode {
if sbt.k == k {
sbt.v = v // set new value
return sbt
}
newNode := &StringyBTreeNode{k: k, v: v}
if sbt.k > k {
if sbt.left == nil {
sbt.left = newNode
} else {
sbt.left.(*StringyBTreeNode).Insert(k, v)
}
}
if sbt.k < k {
if sbt.right == nil {
sbt.right = newNode
} else {
sbt.right.(*StringyBTreeNode).Insert(k, v)
}
}
return sbt
}
func (sbt *StringyBTreeNode) Get(k string) interface{} {
if sbt.k == k {
return sbt.v
}
if sbt.k > k {
if sbt.left != nil {
return sbt.left.(*StringyBTreeNode).Get(k)
}
}
if sbt.k < k {
if sbt.right != nil {
return sbt.right.(*StringyBTreeNode).Get(k)
}
}
return nil // not found
}

25
datastructures_test.go Normal file
View File

@ -0,0 +1,25 @@
package main
import (
"testing"
)
func TestBuildingTree(t *testing.T) {
tree := NewStringyBTree("foo", 1).Insert("bar", 2).Insert("baz", 3).Insert("quuz", 4)
if tree.Get("foo") != 1 {
t.Fail()
}
if tree.Get("bar") != 2 {
t.Fail()
}
if tree.Get("baz") != 3 {
t.Fail()
}
if tree.Get("quuz") != 4 {
t.Fail()
}
tree.Insert("bar", 5)
if tree.Get("bar") != 5 {
t.Fail()
}
}

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module tpop
go 1.16