The Computer Language
Benchmarks Game

binary-trees Go #9 program

source code

/* The Computer Language Benchmarks Game
 * http://benchmarksgame.alioth.debian.org/
 *
 * contributed by Ugorji Nwoke
 * *reset*
 */

package main

import (
   "fmt"
   "os"
   "strconv"
)

const minDepth = 4

type treeNode struct {
   left, right *treeNode
}

func (n *treeNode) itemCheck() int {
   if n.left == nil {
      return 1
   }
   return 1 + n.left.itemCheck() + n.right.itemCheck()
}

func bottomUp(depth int) *treeNode {
   if depth > 0 {
      return &treeNode{
         bottomUp(depth-1),
         bottomUp(depth-1),
      }
   }
   return &treeNode{nil, nil}
}

func main() {
   n := 0
   if len(os.Args) > 1 {
      if n2, err2 := strconv.ParseInt(os.Args[1], 10, 0); err2 == nil {
         n = int(n2)
      }
   }
   maxDepth := n
   if minDepth+2 > n {
      maxDepth = minDepth + 2
   }
   stretchDepth := maxDepth + 1
   check := bottomUp(stretchDepth).itemCheck()
   fmt.Printf("stretch tree of depth %v\t check: %v\n", stretchDepth, check)
   longLivedTree := bottomUp(maxDepth)
   for depth := minDepth; depth <= maxDepth; depth += 2 {
      interactions := 1 << uint(maxDepth-depth+minDepth)
      check = 0
      for i := 1; i <= interactions; i++ {
         check += bottomUp(depth).itemCheck()
      }
      fmt.Printf("%v\t trees of depth %v\t check: %v\n", interactions, depth, check)
   }
   fmt.Printf("long lived tree of depth %v\t check: %v\n", maxDepth, longLivedTree.itemCheck())
}
    

notes, command-line, and program output

NOTES:
64-bit Ubuntu quad core
go version go1.8 linux/amd64


Sat, 25 Mar 2017 00:49:34 GMT

MAKE:
/usr/local/src/go/bin/go build -o binarytrees.go-9.go_run
2.43s to complete and log all make actions

COMMAND LINE:
./binarytrees.go-9.go_run 21

PROGRAM OUTPUT:
stretch tree of depth 22	 check: 8388607
2097152	 trees of depth 4	 check: 65011712
524288	 trees of depth 6	 check: 66584576
131072	 trees of depth 8	 check: 66977792
32768	 trees of depth 10	 check: 67076096
8192	 trees of depth 12	 check: 67100672
2048	 trees of depth 14	 check: 67106816
512	 trees of depth 16	 check: 67108352
128	 trees of depth 18	 check: 67108736
32	 trees of depth 20	 check: 67108832
long lived tree of depth 21	 check: 4194303