package main
import "fmt"
func main(){
tree := NewBinaryTree()
test(!tree.Contains(0), "not contains 0")
test(!tree.Contains(42), "not contains 42")
fmt.Println("# adding 42")
tree.Add(42)
test(tree.Contains(42), "contains 42")
test(!tree.Contains(17), "not contains 17")
fmt.Println("# adding 17")
tree.Add(17)
test(tree.Contains(17), "contains 17")
test(tree.Contains(42), "contains 42")
}
func test(expr bool, text string) {
if expr {
fmt.Println("OK -- " + text)
} else {
fmt.Println("FAIL -- " + text)
}
}
// everything below would typically be in a separate package
type BinaryTree struct {
root *node
}
func NewBinaryTree() *BinaryTree {
return &BinaryTree { nil }
}
type node struct {
value int
left, right *node
}
func (node *node) getNode(i int) **node {
if node.value < i {
if node.left == nil {
return &node.left
}
return node.left.getNode(i)
} else if i < node.value {
if node.right == nil {
return &node.right
}
return node.right.getNode(i)
}
return &node // not nil, not writable
}
func (tree *BinaryTree) Contains(n int) bool {
root := tree.root
if root == nil {
return false
}
return *(root.getNode(n)) != nil
}
// returns true if the tree was mutated as a result,
// and false if the number was already present
func (tree *BinaryTree) Add(n int) bool {
if tree.root == nil {
tree.root = &node{n, nil, nil}
return true
}
target := tree.root.getNode(n)
if *target == nil {
*target = &node{n, nil, nil}
return true
}
return false
}
cGFja2FnZSBtYWluCmltcG9ydCAiZm10IgoKZnVuYyBtYWluKCl7Cgl0cmVlIDo9IE5ld0JpbmFyeVRyZWUoKQoJdGVzdCghdHJlZS5Db250YWlucygwKSwgIm5vdCBjb250YWlucyAwIikKCQoJdGVzdCghdHJlZS5Db250YWlucyg0MiksICJub3QgY29udGFpbnMgNDIiKQoJZm10LlByaW50bG4oIiMgYWRkaW5nIDQyIikKCXRyZWUuQWRkKDQyKQoJdGVzdCh0cmVlLkNvbnRhaW5zKDQyKSwgImNvbnRhaW5zIDQyIikKCQoJdGVzdCghdHJlZS5Db250YWlucygxNyksICJub3QgY29udGFpbnMgMTciKQoJZm10LlByaW50bG4oIiMgYWRkaW5nIDE3IikKCXRyZWUuQWRkKDE3KQoJdG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