import java.io.PrintStream; public class RandomTree { private class Node { /** * value of the node, in this case an integer. */ private int value = 0; /** * */ private int level = 0; /** * Stores a reference to its left node. */ private Node left = null; /** * Stores a reference to its right node. */ private Node right = null; /** * Constructor for the node class. * @param value Used to change the value of the node. */ public Node(int value, int level) { this.value = value; this.level = level; } /** * Inserts the new value for the tree and prints the sequence to reach that number. * @param value it's the new value wanted to be stored in the tree. * @param out used to print the value of the node and if the value goes to the right(+) or left(-). */ public void insert(int value, PrintStream out) { int random = (int)(Math.random() * 100); // Print the value of the current Node out.printf("%d ", this.value); if(random % 2 == 0) { out.print("-"); if(left == null) { out.printf("%d", value); left = new Node(value, this.level + 1); } else left.insert(value, out); } else { out.print("+"); if(right == null) { out.printf("%d", value); right = new Node(value, this.level + 1); } else right.insert(value, out); } } /** * It gets the depth for a given node. * @return the depth for the node. */ public int getTreeDepth() { if(left == null && right != null) { return right.getTreeDepth(); } else if (left != null && right == null) { return left.getTreeDepth(); } else if(left == null && right == null) { return this.level; } else { return Math.max(left.getTreeDepth(), right.getTreeDepth()); } } } /** * Stores the reference of the root. */ Node root = null; /** * It inserts a new value and prints the sequence to get to its new position. * @param newNumber its the new value to insert in the tree. * @param out used to print the sequence. */ public void insert(int newNumber, PrintStream out) { if(isEmpty()) { out.print(newNumber); root = new Node(newNumber, 0); } else { root.insert(newNumber, out); } } /** * It eliminates the tree (changes the root to null). */ public void resetTree() { root = null; } /** * It gets the highest value for the depth of the tree. * @return -1 if the tree doesn't have a root, 0 if it only has a root, else the value for the depth. */ public int getTreeDepth() { if(isEmpty()) { return -1; } else { return root.getTreeDepth(); } } /** * Checks if the tree has a root. * @return true if the there is a root, false if there isn't. */ public boolean isEmpty() { return root == null; } }