Advertisement
Guest User

Untitled

a guest
Feb 25th, 2017
95
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. rupalbarman@gmail.com
  5. */
  6.  
  7. package main
  8.  
  9. import (
  10. "fmt"
  11. "math/rand"
  12. )
  13.  
  14.  
  15. type Tree struct {
  16. Left *Tree
  17. Value int
  18. Right *Tree
  19. }
  20.  
  21.  
  22. func New(n, k int) *Tree {
  23. var t *Tree
  24. for _, v := range rand.Perm(n) {
  25. t = insert(t, v)
  26. }
  27. return t
  28. }
  29.  
  30. func insert(t *Tree, v int) *Tree {
  31. if t == nil {
  32. return &Tree{nil, v, nil}
  33. }
  34. if v < t.Value {
  35. t.Left = insert(t.Left, v)
  36. return t
  37. }
  38. t.Right = insert(t.Right, v)
  39. return t
  40. }
  41.  
  42. func inorder(t *Tree) {
  43. if t!=nil{
  44. inorder(t.Left)
  45. fmt.Println(t.Value)
  46. inorder(t.Right)
  47. }
  48. }
  49.  
  50. func preorder(t *Tree) {
  51. if t!=nil{
  52. preorder(t.Left)
  53. preorder(t.Right)
  54. fmt.Println(t.Value)
  55. }
  56. }
  57.  
  58. func main() {
  59. t := New(10, 1)
  60. fmt.Println("Preorder")
  61. preorder(t)
  62. fmt.Println("Inorder")
  63. inorder(t)
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement