Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
2.6 kB
1
Indexable
Never
package main

import (
    "fmt"
    "math/rand"
    "time"
    "strings"
)

type bitreeNode struct {
  left *bitreeNode
  right *bitreeNode
  val int
}

type bitree struct {
  root *bitreeNode
}

func arr2tree (a []int, i int) (root *bitreeNode) {
   if i >= len(a) {
     return nil
   }

   //left  a[2*i+1]
   //right  a[2*i+2]

   root = &bitreeNode{nil,nil,a[i]}
   root.left = arr2tree(a,2*i+1)
   root.right = arr2tree(a,2*i+2)
   return root
}

func randSlice() []int {
  rando := []int{}

  for i := 0 ; i < 50 ; i++{
    rando = append(rando, rand.Intn(101))
  }
  return rando
}

func stampaAlberoASommario (node *bitreeNode, spaces int){
  //node è la mia radice
  fmt.Print(strings.Repeat(" ",spaces))
  fmt.Print("*")
  fmt.Println(node.val)

  if node.right == nil && node.left == nil{
    return
  }

  if node.right != nil {
    stampaAlberoASommario(node.right,spaces+2)
  }else {
    fmt.Print(strings.Repeat(" ",spaces+2))
    fmt.Println("*")
  }
  if node.left != nil {
    stampaAlberoASommario(node.left,spaces+2)
  }else {
    fmt.Print(strings.Repeat(" ",spaces+2))
    fmt.Println("*")
  }
}

func stampaDiSostegno(spaces int,depth int){
  x := 0
  for i:=0 ; i < depth ; i++{
  fmt.Print(strings.Repeat(" ",x+2))
  fmt.Print("|")
}
}

func stampaAlberoASommario2 (node *bitreeNode, spaces int,depth int){
  //node è la mia radice
  stampaDiSostegno(spaces,depth)

    //fmt.Print(strings.Repeat(" ",spaces))
  fmt.Print(strings.Repeat("_",spaces))

  fmt.Println(node.val)

  if node.right == nil && node.left == nil{
    return
  }

  if node.right != nil {
    stampaAlberoASommario2(node.right,spaces+2, depth+1)
  }else {
    //stampaDiSostegno(spaces,depth)

/*
    fmt.Print(strings.Repeat(" ",spaces+2))
    fmt.Print("|")*/
    //depth := 0
    stampaDiSostegno(spaces,depth+1)
    fmt.Print(strings.Repeat("_",spaces+2))
    fmt.Println("*")
  }


  if node.left != nil {
    stampaAlberoASommario2(node.left,spaces+2, depth+1)
  }else {/*
    fmt.Print(strings.Repeat(" ",spaces+2))
    fmt.Print("|")*/
    //depth := 0
    stampaDiSostegno(spaces,depth+1)
    fmt.Print(strings.Repeat("_",spaces+2))
    fmt.Println("*")
  }
  

}


func main () {
  //Seed
  rand.Seed(time.Now().UnixNano())

  //v := randSlice()
  //fmt.Println(randomSlice)
  v := []int{69,89,28,39,66,44,12,2,72}
  //v := []int{78,54,21,90,19,95}
  //v := []int{69,89,69,12,54,12,1,3}
  fmt.Println(v)
  a := arr2tree(v,0)
  //fmt.Println(a.left.left.left, a.right.right)
  //stampaAlberoASommario(a,0)
  stampaAlberoASommario2(a,0,0)

}