// Package binarysearchtree implements a binary search tree.
package binarysearchtree
// SearchTreeData represents an enrty in the tree.
type SearchTreeData struct {
left *SearchTreeData
data int
right *SearchTreeData
}
// Bst creates a new binary search tree with input as the root node value.
func Bst(input int) *SearchTreeData {
return &SearchTreeData{data: input}
}
// Insert inserts elem to the BST.
func (t *SearchTreeData) Insert(elem int) {
if elem <= t.data {
if t.left == nil {
t.left = &SearchTreeData{data: elem}
return
}
t.left.Insert(elem)
} else {
if t.right == nil {
t.right = &SearchTreeData{data: elem}
return
}
t.right.Insert(elem)
}
}
func (t *SearchTreeData) MapString(f func(int) string) []string {
var ret []string
for _, elem := range t.inorder() {
ret = append(ret, f(elem))
}
return ret
}
func (t *SearchTreeData) MapInt(f func(int) int) []int {
var ret []int
for _, elem := range t.inorder() {
ret = append(ret, f(elem))
}
return ret
}
func (t *SearchTreeData) inorder() []int {
ret := &[]int{}
var recurse func(*SearchTreeData, *[]int)
recurse = func(node *SearchTreeData, ret *[]int) {
if node == nil {
return
}
recurse(node.left, ret)
*ret = append(*ret, node.data)
recurse(node.right, ret)
}
recurse(t, ret)
return *ret
}