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:
private
static
class
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
}
... {
...
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
}
Here is the insert method:
private
BinaryNode
<
T
>
insert(T x, BinaryNode
<
T
>
t, BinaryNode
<
T
>
larger, BinaryNode
<
T
>
smaller)
... {
if (t == null)
...{
BinaryNode<T> n = new BinaryNode<T>(x, null, null, larger, smaller);
if (larger != null) larger.prev = n;
if (smaller != null) smaller.next = n;
return n;
}
int compareResult = x.compareTo(t.element);
if (compareResult < 0)
t.left = insert(x, t.left, t, smaller);
else if (compareResult > 0)
t.right = insert(x, t.right, larger, t);
else
; // duplicate
return t;
}
... {
if (t == null)
...{
BinaryNode<T> n = new BinaryNode<T>(x, null, null, larger, smaller);
if (larger != null) larger.prev = n;
if (smaller != null) smaller.next = n;
return n;
}
int compareResult = x.compareTo(t.element);
if (compareResult < 0)
t.left = insert(x, t.left, t, smaller);
else if (compareResult > 0)
t.right = insert(x, t.right, larger, t);
else
; // duplicate
return t;
}
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.