Skip to content

Instantly share code, notes, and snippets.

@tangingw
Last active May 23, 2017 04:41
Show Gist options
  • Save tangingw/71a4ff02d608138f723a57403416bad9 to your computer and use it in GitHub Desktop.
Save tangingw/71a4ff02d608138f723a57403416bad9 to your computer and use it in GitHub Desktop.
This is a simple implementation of binary tree search algorithm in Golang
package main
import (
"fmt"
)
/*
Reference:
1. http://0xax.blogspot.my/2014/08/binary-tree-and-some-generic-tricks.html
2. https://www.tutorialspoint.com/data_structures_algorithms/tree_traversal.htm
*/
type Node struct {
Left *Node
Right *Node
Value interface{}
}
func (n *Node) Insert(value interface{}) {
if n.Value == nil {
n.Value = value
n.Left = newNode()
n.Right = newNode()
} else {
if value.(int) < n.Value.(int) {
n.Left.Insert(value)
} else {
n.Right.Insert(value)
}
}
}
func (n *Node) Search(value int) int {
if n.Value == nil {
return 0
}
if n.Value.(int) == value {
return 1
} else {
if n.Value.(int) < value {
t := n.Right.Search(value)
return t
} else {
t := n.Left.Search(value)
return t
}
}
}
/**
Example of a tree:
A
/ \
B C
/ \ / \
D E F G
**/
func printInorder(n *Node) {
/*
Sequeunce of the in order traversal:
D -> B -> E -> A -> F -> C -> G
*/
if n.Value != nil {
printInorder(n.Left)
fmt.Println(n.Value)
printInorder(n.Right)
}
}
func printPreorder(n *Node) {
/*
Sequence of the Pre-Order Traversal:
A-> B -> D -> E -> C -> F -> G
*/
if n.Value != nil {
fmt.Println(n.Value)
printPreorder(n.Left)
printPreorder(n.Right)
}
}
func printPostorder(n *Node) {
/*
Sequence of the Post-Order Transversal
D -> E -> B -> F -> G -> C -> A
*/
if n.Value != nil {
printPostorder(n.Left)
printPostorder(n.Right)
fmt.Println(n.Value)
}
}
func newNode() *Node {
n := &Node{}
return n
}
func main() {
node := newNode()
node.Insert(50) //the key for the root
//All these are leaves
node.Insert(40)
node.Insert(80)
node.Insert(100)
node.Insert(60)
node.Insert(70)
node.Insert(30)
printInorder(node)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment