/** * An (inverse) ordered binary tree. * * @author Marcus */ public class Tree { /** * The root node of the tree. */ private TreeNode root; /** * Creates a new and empty tree. */ public Tree() { super(); } /** * Traverses the tree and calls the visitor's * visit(TreeNode) method in post-order. * * @param visitor The visitor whose visit method * shall be called in post-order. */ public void traverse(TreeVisitor visitor) { traverse(visitor, root); } /** * Traverses the subtree starting at current * and calls the visitor's visit(TreeNode) * method in post-order. * * @param visitor The visitor. * @param current The subtree to visit, may be null. */ private void traverse(TreeVisitor visitor, TreeNode current) { if (current == null) return; // TODO: implement } /** * Inserts a new value into the tree. * * @param value The value to insert. */ public void insert(double value) { if (root == null) { root = new TreeNode(value); } else { insert(value, root); } } /** * Recursively finds the right node to insert the * value and inserts it. * * @param value The value to insert. * @param current The current value. */ private void insert(double value, TreeNode current) { if (value > current.getValue()) { // larger values go left if (current.getLeft() == null) { current.setLeft(new TreeNode(value)); } else { insert(value, current.getLeft()); } } else { // smaller or equal values go right if (current.getRight() == null) { current.setRight(new TreeNode(value)); } else { insert(value, current.getRight()); } } } /** * Efficiently counts the number of nodes in the * tree that have a particular value by considering * the order that is defined by the tree's insert * method. * * @param value The value to search from. * @return The number of nodes with the value. */ public int count(double value) { return count(value, root); } /** * Efficiently counts the number of nodes in the * subtree starting at current that have a particular * value by considering the order that is defined * by the tree's insert method. * * @param value The value to search from. * @param current The subtree to search in, may be null. * @return The number of nodes with the value. */ private int count(double value, TreeNode current) { if (current == null) return 0; // TODO: implement return -1; } /** * Calculates the height of the tree total tree. * * @return The height of the tree, which is the * number of edges on the longest path from the root * to a leaf node. If the tree is empty, returns 0. * If the tree has only one node, returns 1. */ public int height() { return height(root); } /** * Calculates the height of the subtree * starting at current. * * @param current The subtree to calculate the height of, may be null. * If null, the height is 0. * @return The height of the subtree, which is the * number of edges on the longest path from the current node * to a leaf node. */ public int height(TreeNode current) { // TODO: implement return -42; } }