// Textbook fragment 07.16 /** * An implementation of the BinaryTree interface by means of a linked structure . */ public class LinkedBinaryTree implements BinaryTree { protected BTPosition root; // reference to the root protected int size; // number of nodes /** Creates an empty binary tree. */ public LinkedBinaryTree() { root = null; // start with an empty tree size = 0; } /** Returns the number of nodes in the tree. */ public int size() { return size; } /** Returns whether a node is internal. */ public boolean isInternal(Position v) throws InvalidPositionException { checkPosition(v); // auxiliary method return (hasLeft(v) || hasRight(v)); } /** Returns whether a node is the root. */ public boolean isRoot(Position v) throws InvalidPositionException { checkPosition(v); return (v == root()); } /** Returns whether a node has a left child. */ public boolean hasLeft(Position v) throws InvalidPositionException { BTPosition vv = checkPosition(v); return (vv.getLeft() != null); } /** Returns the root of the tree. */ public Position root() throws EmptyTreeException { if (root == null) throw new EmptyTreeException("The tree is empty"); return root; } /** Returns the left child of a node. */ public Position left(Position v) throws InvalidPositionException, BoundaryViolationException { BTPosition vv = checkPosition(v); Position leftPos = vv.getLeft(); if (leftPos == null) throw new BoundaryViolationException("No left child"); return leftPos; }