public BinarySearchTree<Node,T> chop(T x)
我在 element实现了将我的树分成两部分x
。SSetthis
将包含元素 < x
,返回的 SSet 是一个包含元素 >= 的 SSet x
。这应该适用于所有元素,无论它们是否在this
.
例如,假设s={2,4,6,8}
. 然后s.chop(3)
返回{4,6,8}
并s
变为{2}
。我们会得到相同的结果s.chop(4)
。
该slowChop
方法实现了,但是它的时间复杂度是O(n),但是我需要在树平衡的时候将它降低到至少O(h)(树h
的高度在哪里)。
public BinarySearchTree<Node,T> slowChop(T x) {
Node sample = super.newNode();
BinarySearchTree<Node,T> other = new
BinarySearchTree<Node, T>(sample);
// Iterate through the n nodes in-order.
// When see value >=x, add to new BST in O(height) time, and
// remove it from this BST (on next iteration) in O(height) time.
Iterator<T> it = iterator();
T prev = null;
while( it.hasNext() ) {
T curr = (T)(it.next());
if( c.compare(curr, x) >= 0 ) { // we have our first >= x
other.add(curr);
if( prev != null ) {
this.remove(prev); // safe to remove now
}
prev = curr;
}
}
if( prev != null ) {
this.remove(prev); // edge case, get that last one!
}
return other;
}
public BinarySearchTree<Node,T> chop(T x) {
Node sample = super.newNode();
BinarySearchTree<Node,T> other = new
BinarySearchTree<Node, T>(sample);
// TODO: Implement this method. It should match slowChop in
// behaviour, but should be faster :-)
return other;
}