Skip to content

Instantly share code, notes, and snippets.

@17twenty
Last active November 6, 2015 03:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 17twenty/e75f5e926eb875c4b1e5 to your computer and use it in GitHub Desktop.
Save 17twenty/e75f5e926eb875c4b1e5 to your computer and use it in GitHub Desktop.
Search/Insert and Traverse
package main
import (
"fmt"
"log"
)
type Node struct {
left *Node
right *Node
Value int
}
func (n *Node) Search(val int) bool {
if n == nil {
return false
}
if n.Value == val {
return true
} else if val < n.Value {
return n.left.Search(val)
} else {
return n.right.Search(val)
}
}
func (n *Node) Insert(val int) {
if val < n.Value {
if n.left != nil {
n.left.Insert(val)
} else {
n.left = &Node{Value: val}
}
}
if val > n.Value {
if n.right != nil {
n.right.Insert(val)
} else {
n.right = &Node{Value: val}
}
}
}
type callback func(int)
func (n *Node) Traverse(f callback) {
if n == nil {
return
}
n.left.Traverse(f)
f(n.Value)
n.right.Traverse(f)
}
func main() {
foo := &Node{}
log.Println("Found:", foo.Search(5))
foo.Insert(5)
log.Println("Found:", foo.Search(5))
log.Println("Found:", foo.Search(12))
foo.Insert(12)
log.Println("Found:", foo.Search(12))
log.Println("Found:", foo.Search(11))
foo.Insert(11)
log.Println("Found:", foo.Search(11))
foo.Traverse(func(Val int) {
fmt.Printf("%d\n", Val)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment