The major hurdle is that our class does not implement Iterable. To overcome this, we augment the BinaryNode inner class by adding links to the next smallest and next largest nodes so that the iterator can efficiently return the next node (just like a linked list). Rewrite the insert method of MyBinarySearchTree to support the added links.
We first augment the data structure so that the inner class becomes:
privatestaticclass BinaryNode ...{ ... AnyType element; // The data in the node BinaryNode<AnyType> left; // Left child BinaryNode<AnyType> right; // Right child BinaryNode<AnyType> smaller; // Previous in-order element BinaryNode<AnyType> larger; // Next in-order element }
When a new node is inserted as a left child, three things must be done to support this augmentation: its larger field must point to its parent; its smaller field must be set to its parent's smaller field; and the parent's smaller field must be set to it. A similar triplet of changes is needed when the new node is a right child.