89 lines
1.4 KiB
Go
89 lines
1.4 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
)
|
|
|
|
type TreeNode interface {
|
|
Left() TreeNode
|
|
Right() TreeNode
|
|
Print(io.Writer)
|
|
}
|
|
|
|
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) Print(w io.Writer) {
|
|
fmt.Printf("%+v\n", sbt)
|
|
if sbt.left != nil {
|
|
sbt.left.Print(w)
|
|
}
|
|
if sbt.right != nil {
|
|
sbt.right.Print(w)
|
|
}
|
|
}
|
|
|
|
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
|
|
}
|