import java.util.Scanner; public class Tree { /** * Reference to the tree's root. */ Node root = null; int topLeaf = 0; /** * A node for the random tree. * Stores a number and knows its children. */ private class Node { private int value = 0; private Node left = null; private Node right = null; private int depth = 0; public Node(int value,int count) { this.value = value; this.depth = count; if (this.depth > topLeaf) { topLeaf = this.depth; } } public void insert(int newNumber, int count) { ++count; if (Math.random() < 0.5) { if (this.left == null) { System.out.printf("%d-%d",this.value, newNumber); this.left = new Node(newNumber, count); } else { System.out.printf("%d-", this.value); this.left.insert(newNumber, count); } } else { if (this.right == null) { System.out.printf("%d+%d", this.value, newNumber); this.right = new Node(newNumber, count); } else { System.out.printf("%d+",this.value); this.right.insert(newNumber, count); } } } } public void reset() { this.root = null; } public void addNode(Scanner input) { System.out.println("Digit positive the number you want to add to the tree"); int newNumber = input.nextInt(); if (newNumber>=0) { if (this.root == null) { this.root = new Node(newNumber, 0); System.out.printf("The destination is:%n%d%n ",newNumber); } else { System.out.println("The destination is:"); this.root.insert(newNumber, 0); System.out.println(); } } else { System.out.println("Invalid number"); } } public void showTopLeaf() { System.out.printf("The farthest leaf is on %d%n", this.topLeaf); } }