tpop/datastructures.go

73 lines
1.2 KiB
Go

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
}