class BinaryTree { protected T value; protected BinaryTree left; protected BinaryTree right; /** * Constructs a BinaryTree node with the * given value. */ public BinaryTree(T value) { this.value = value; } /** * Gets the value */ public T value() { return value; } /** * Sets the left subtree. */ public void setLeft(BinaryTree t) { left = t; } /** * Sets the right subtree. */ public void setRight(BinaryTree t) { right = t; } /** * Gets the left subtree. */ public BinaryTree getLeft() { return left; } /** * Gets the right subtree. */ public BinaryTree getRight() { return right; } /** * Get the number of elements in this tree. */ public int size() { int l = 0; int r = 0; if (left != null) { l = left.size(); } if (right != null) { r = right.size(); } return 1 + l + r; } /** * Returns a string representation of a binary tree. */ public String toString() { /*// (v l r) String l = "ε"; String r = "ε"; if (left != null) { l = left.toString(); } if (right != null) { r = right.toString(); } return "(" + value.toString() + " " + l + " " + r + ")"; */ return toStringHelper(0); } /** * Returns a string representation of the * subtree at the given indentation level. * * @param level Indentation level. */ protected String toStringHelper(int level) { String l = "ε"; String r = "ε"; String s = ""; String spaces = ""; Boolean hasChildren = false; // get indent spaces += "\n"; for (int i = 0; i < level; i++) { spaces += " "; } // get substring for left tree if (left != null) { l = left.toStringHelper(level + 1); hasChildren = true; } // get substring for right tree if (right != null) { r = right.toStringHelper(level + 1); hasChildren = true; } // print this tree s += spaces + "(" + value.toString() + " "; // print children s += l + " " + r; // if we had children, indent last parens if (hasChildren) { s += spaces; } s += ")"; return s; } }