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
}
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;
}

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.
本文介绍如何通过增加节点间的链接来使二叉搜索树支持迭代器接口,包括修改内部BinaryNode类以包含指向下一个最小和最大节点的指针,并重写插入方法以维护这些新增的链接。
2152

被折叠的 条评论
为什么被折叠?



