Skip to content

Instantly share code, notes, and snippets.

@capoferro
Created December 4, 2013 17:12
Show Gist options
  • Select an option

  • Save capoferro/7791451 to your computer and use it in GitHub Desktop.

Select an option

Save capoferro/7791451 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func (t *TreeNode) Insert(node *TreeNode) {
if node.Val > t.Val {
if t.Right == nil {
t.Right = node
} else {
t.Right.Insert(node)
}
} else {
if t.Left == nil {
t.Left = node
} else {
t.Left.Insert(node)
}
}
}
func (t *TreeNode) Find(i int) *TreeNode {
fmt.Printf("Processing %v\n", t)
if i == t.Val {
return t
} else if i > t.Val && t.Right != nil{
return t.Right.Find(i)
} else if i < t.Val && t.Left != nil{
return t.Left.Find(i)
} else {
return nil
}
}
func main() {
tree := &TreeNode{Val: 2}
for _, n := range [...]int{2,1,4,3,5,1,3,1,9} {
tree.Insert(&TreeNode{Val: n})
}
fmt.Printf("Finding 9: %v\n", tree.Find(9))
fmt.Printf("Finding 10: %v\n", tree.Find(10))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment