Last active
February 25, 2017 13:51
-
-
Save rupalbarman/f768a822c779b01c1e8089b610b141f6 to your computer and use it in GitHub Desktop.
Binary Search Tree golang
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
| /* | |
| 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