Last active
November 6, 2015 03:13
-
-
Save 17twenty/e75f5e926eb875c4b1e5 to your computer and use it in GitHub Desktop.
Search/Insert and Traverse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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