The Computer Language
24.04 Benchmarks Game

binary-trees Java #2 program

source code

/* The Computer Language Benchmarks Game
   https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
 
   contributed by Jarkko Miettinen
   *reset*
*/

public class binarytrees {

   private final static int minDepth = 4;
   
   public static void main(String[] args){
      int n = 0;
      if (args.length > 0) n = Integer.parseInt(args[0]);
      
      int maxDepth = (minDepth + 2 > n) ? minDepth + 2 : n;
      int stretchDepth = maxDepth + 1;
      
      int check = (TreeNode.bottomUpTree(stretchDepth)).itemCheck();
      System.out.println("stretch tree of depth "+stretchDepth+"\t check: " + check);
      
      TreeNode longLivedTree = TreeNode.bottomUpTree(maxDepth);
      
      for (int depth=minDepth; depth<=maxDepth; depth+=2){
         int iterations = 1 << (maxDepth - depth + minDepth);
         check = 0;
         
         for (int i=1; i<=iterations; i++){
            check += (TreeNode.bottomUpTree(depth)).itemCheck();
         }
         System.out.println(iterations + "\t trees of depth " + depth + "\t check: " + check);
      }   
      System.out.println("long lived tree of depth " + maxDepth + "\t check: "+ longLivedTree.itemCheck());
   }
   
   
   private static class TreeNode
   {
      private TreeNode left, right;
      
      private static TreeNode bottomUpTree(int depth){
         if (depth>0){
            return new TreeNode(
                  bottomUpTree(depth-1)
                  , bottomUpTree(depth-1)
            );
         }
         else {
            return new TreeNode(null,null);
         }
      }
      
      TreeNode(TreeNode left, TreeNode right){
         this.left = left;
         this.right = right;
      }
      
      private int itemCheck(){
         // if necessary deallocate here
         if (left==null) return 1;
         else return 1 + left.itemCheck() + right.itemCheck();
      }
   }
}
    

notes, command-line, and program output

NOTES:
64-bit Ubuntu quad core
java 22 2024-03-19
Java HotSpot(TM) 64-Bit Server VM
(build 22+36-2370, 
mixed mode, sharing)


 Wed, 20 Mar 2024 02:08:30 GMT

MAKE:
mv binarytrees.java-2.java binarytrees.java
/opt/src/jdk-22/bin/javac -d . -cp . binarytrees.java

1.57s to complete and log all make actions

COMMAND LINE:
 /opt/src/jdk-22/bin/java  -cp . binarytrees 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