The Computer Language
24.11 Benchmarks Game

binary-trees Java -Xint #8 program

source code

/* The Computer Language Benchmarks Game
   https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
 
   contributed by Isaac Gouy
*/

final class Tree {
   Tree left, right;
      
   Tree(Tree left, Tree right){
      this.left = left;
      this.right = right;
   }      
      
   static Tree with(int depth){
      return (depth == 0) 
         ? new Tree(null, null)
         : new Tree(with(depth-1), with(depth-1));
   }
            
   int nodeCount(){
      return (left == null)
         ? 1 
         : 1 + left.nodeCount() + right.nodeCount();
   }
   
   void clear(){
      if (left != null) {
         left.clear(); 
         left = null;
         right.clear();
         right = null;         
      }
   }   
}

final class binarytrees {   
   public static void main(String[] args){
      int n = 10;
      if (args.length > 0) n = Integer.parseInt(args[0]);

      int minDepth = 4;
      int maxDepth = (minDepth + 2 > n) ? minDepth + 2 : n;
      int stretchDepth = maxDepth + 1;
      
      stretch(stretchDepth);
      var longLivedTree = Tree.with(maxDepth);
      
      for (int depth = minDepth; depth <=maxDepth; depth += 2) {
         int iterations = 1 << (maxDepth - depth + minDepth);
         int sum = 0;
         for (int i = 1; i <= iterations; i++){
            sum += count(depth);          
         }
         System.out.println(iterations + "\t trees of depth " 
               + depth + "\t check: " + sum);
      }   
      int count = longLivedTree.nodeCount();    
      longLivedTree.clear();       
      System.out.println("long lived tree of depth " 
            + maxDepth + "\t check: "+ count);              
   }
   
   static void stretch(int depth){         
      System.out.println("stretch tree of depth " 
            + depth +"\t check: " + count(depth));   
   }
   
   static int count(int depth){
      var t = Tree.with(depth);         
      int c = t.nodeCount();
      t.clear(); 
      return c;
   }   
}   
    

notes, command-line, and program output

NOTES:
64-bit Ubuntu quad core
java 23 2024-09-17
Java HotSpot(TM) 64-Bit Server VM
(build 23+37-2369, 
interpreted mode, sharing)


 Mon, 14 Oct 2024 01:55:23 GMT

MAKE:
mv binarytrees.javaxint-8.javaxint binarytrees.java
/opt/src/jdk-23/bin/javac -d . -cp .  binarytrees.java

2.84s to complete and log all make actions

COMMAND LINE:
 /opt/src/jdk-23/bin/java -Xint  -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