Main class for testing:
public class Main { public static void main(String[] args) { final int TRIALS = 1; final int NUMBERS = 10000; double sum = 0; // adding up all of the depths for (int i = 0; i < TRIALS; i++) { Randp rand = new Randp(NUMBERS); BST<Integer> bst = new BST<Integer>(rand.nextInt()); while (rand.numsLeft() > 0) { bst.insert(rand.nextInt()); } sum += bst.depth(); } System.out.println(sum / TRIALS); } }
Binary search tree class:
public class BST<T extends Comparable<T>> { private T datum; private BST<T> left; private BST<T> right; public BST(T datum) { this.datum = datum; left = null; right = null; } public BST(T datum, BST<T> left, BST<T> right) { this.datum = datum; this.left = left; this.right = right; } public T getDatum() { return datum; } public BST<T> getLeft() { return left; } public BST<T> getRight() { return right; } public boolean isLeaf() { return (getLeft() == null) && (getRight() == null); } public void insert(T datum) { if (this.datum.compareTo(datum) > 0) { if (left != null) { left.insert(datum); } else { left = new BST<T>(datum); } } else if (this.datum.compareTo(datum) < 0) { if (right != null) { right.insert(datum); } else { right = new BST<T>(datum); } } } public int depth() { return (1 + (Math.max( left == null ? 0 : left.depth(), right == null ? 0 : right.depth()))); } public boolean contains(T datum) { if (datum.compareTo(this.datum) < 0) { if (left == null) { return false; } else { return left.contains(datum); } } else if (datum.compareTo(this.datum) > 0) { if (right == null) { return false; } else { return right.contains(datum); } } else { return true; } } public void printInOrder() { // (6 + 3) if (left != null) left.printInOrder(); System.out.print(datum + " "); if (right != null) right.printInOrder(); } public void printPreOrder() { // (+ 6 3) postorder: (6 3 +) System.out.print(datum + " "); if (left != null) left.printPreOrder(); if (right != null) right.printPreOrder(); } public void printPostOrder() { // (+ 6 3) postorder: (6 3 +) if (left != null) left.printPreOrder(); if (right != null) right.printPreOrder(); System.out.print(datum + " "); } public String toString() { return "Tree with root " + datum; } }
Randp class (with numsLeft() method added)
public class Randp { private int numsLeft; private int[] nums; public Randp(int n) { numsLeft = n; initNums(); } private void initNums() { nums = new int[numsLeft]; for (int i = 0; i < nums.length; i++) { nums[i] = i+1; } } public int nextInt() { if (numsLeft == 0) return 0; int index = (int) (numsLeft * Math.random()); numsLeft--; swap(nums,index,numsLeft); return nums[numsLeft]; } public int numsLeft() { return numsLeft; } // In case you need to know how many numbers there were originally public int size() { return nums.length; } public void swap(int[] arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } }