Advertisement
Guest User

Untitled

a guest
Feb 25th, 2017
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.78 KB | None | 0 0
  1. /*
  2. Binary Search Tree GoLang
  3. Rupal barman
  4. */
  5.  
  6. package main
  7.  
  8. import (
  9. "fmt"
  10. "math/rand"
  11. )
  12.  
  13.  
  14. type Tree struct {
  15. Left *Tree
  16. Value int
  17. Right *Tree
  18. }
  19.  
  20.  
  21. func New(n, k int) *Tree {
  22. var t *Tree
  23. for _, v := range rand.Perm(n) {
  24. t = insert(t, v)
  25. }
  26. return t
  27. }
  28.  
  29. func insert(t *Tree, v int) *Tree {
  30. if t == nil {
  31. return &Tree{nil, v, nil}
  32. }
  33. if v < t.Value {
  34. t.Left = insert(t.Left, v)
  35. return t
  36. }
  37. t.Right = insert(t.Right, v)
  38. return t
  39. }
  40.  
  41. func inorder(t *Tree) {
  42. if t!=nil{
  43. inorder(t.Left)
  44. fmt.Println(t.Value)
  45. inorder(t.Right)
  46. }
  47. }
  48.  
  49. func preorder(t *Tree) {
  50. if t!=nil{
  51. preorder(t.Left)
  52. preorder(t.Right)
  53. fmt.Println(t.Value)
  54. }
  55. }
  56.  
  57. func main() {
  58. t := New(10, 1)
  59. fmt.Println("Preorder")
  60. preorder(t)
  61. fmt.Println("Inorder")
  62. inorder(t)
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement