Skip to content

Instantly share code, notes, and snippets.

@rupalbarman
Last active February 25, 2017 13:51
Show Gist options
  • Select an option

  • Save rupalbarman/f768a822c779b01c1e8089b610b141f6 to your computer and use it in GitHub Desktop.

Select an option

Save rupalbarman/f768a822c779b01c1e8089b610b141f6 to your computer and use it in GitHub Desktop.
Binary Search Tree golang
/*
Binary Search Tree GoLang
Rupal barman
[email protected]
*/
package main
import (
"fmt"
"math/rand"
)
type Tree struct {
Left *Tree
Value int
Right *Tree
}
func New(n, k int) *Tree {
var t *Tree
for _, v := range rand.Perm(n) {
t = insert(t, v)
}
return t
}
func insert(t *Tree, v int) *Tree {
if t == nil {
return &Tree{nil, v, nil}
}
if v < t.Value {
t.Left = insert(t.Left, v)
return t
}
t.Right = insert(t.Right, v)
return t
}
func inorder(t *Tree) {
if t!=nil{
inorder(t.Left)
fmt.Println(t.Value)
inorder(t.Right)
}
}
func preorder(t *Tree) {
if t!=nil{
preorder(t.Left)
preorder(t.Right)
fmt.Println(t.Value)
}
}
func main() {
t := New(10, 1)
fmt.Println("Preorder")
preorder(t)
fmt.Println("Inorder")
inorder(t)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment