The Computer Language
Benchmarks Game

binary-trees Java #3 program

source code

/* The Computer Language Benchmarks Game
 * http://benchmarksgame.alioth.debian.org/
 *
 * contributed by Jarkko Miettinen
 * modified by Daryl Griffith
 * *reset*
*/

public class binarytrees {

    public static void main(String[] args) {
        int maxDepth;
        
        {
            int n = 0;
            
            if (args.length > 0) {
                n = Integer.parseInt(args[0]);
            }
            maxDepth = (6 > n) ? 6 : n;
        }
        {
            int stretchDepth = maxDepth + 1;

            System.out.println("stretch tree of depth " + stretchDepth + 
		"\t check: " + checkTree(createTree(stretchDepth)));
        }
        trees(maxDepth);
    }
    
    public static void trees(int maxDepth) {
        TreeNode longLastingNode = createTree(maxDepth);
        int depth = 4;

        do {
            int iterations = 16 << (maxDepth - depth);

            loops(iterations, depth);
            depth += 2;
        } while (depth <= maxDepth);
        System.out.println("long lived tree of depth " + maxDepth
		 + "\t check: " + checkTree(longLastingNode));
    }
    
    public static void loops(int iterations, int depth) {
        int check = 0;
        int item = 0;

        do {
            check += checkTree(createTree(depth));
            item++;
        } while (item < iterations);
        System.out.println(iterations + "\t trees of depth " +
		depth + "\t check: " + check);
    }
    
    public static TreeNode createTree(int depth) {
        TreeNode node = new TreeNode();

        if (depth > 0) {
            depth--;
            node.left = createTree(depth);
            node.right = createTree(depth);
        }
        return node;
    }
    
    public static int checkTree(TreeNode node) {
        if (node.left == null) {
            return 1;
        }
        return checkTree(node.left) + checkTree(node.right) + 1;
    }

    public static class TreeNode {

        private int item;
        private TreeNode left, right;
    }
}
    

notes, command-line, and program output

NOTES:
64-bit Ubuntu quad core
java 9
Java(TM) SE Runtime Environment (build 9+181)
Java HotSpot(TM) 64-Bit Server VM (build 9+181, mixed mode)


Thu, 21 Sep 2017 19:17:10 GMT

MAKE:
mv binarytrees.java-3.java binarytrees.java
/usr/local/src/jdk-9/bin/javac -d .  binarytrees.java

0.99s to complete and log all make actions

COMMAND LINE:
/usr/local/src/jdk-9/bin/java   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