/** * This class represents a generic binary tree node. * It is the same class as presented in the 2020-04-20 * lecture, only renamed so that it is clear that we're * talking specifically about nodes. * * We also added a getHeight() static method in class. */ class BinaryTreeNode { protected T value; protected BinaryTreeNode left; protected BinaryTreeNode right; /** * Constructs a BinaryTreeNode node with the * given value. */ public BinaryTreeNode(T value) { this.value = value; } /** * Gets the value */ public T value() { return value; } /** * Sets the left subtree. */ public void setLeft(BinaryTreeNode t) { left = t; } /** * Sets the right subtree. */ public void setRight(BinaryTreeNode t) { right = t; } /** * Gets the left subtree. */ public BinaryTreeNode getLeft() { return left; } /** * Gets the right subtree. */ public BinaryTreeNode 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; } public static int getHeight(BinaryTreeNode t) { if (t == null) { return -1; } int lh = getHeight(t.getLeft()); int rh = getHeight(t.getRight()); int max; if (lh > rh) { max = lh; } else { max = rh; } return max + 1; } }