【发布时间】:2022-01-05 12:02:51
【问题描述】:
我实现了public BinarySearchTree<Node,T> chop(T x)
在元素x 处将我的树分成两部分。 SSet this 将包含元素 x,返回的 SSet 是一个包含元素 >= x 的 SSet。这应该适用于所有元素,无论它们是否在 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;
}
【问题讨论】:
标签: java data-structures binary-tree binary-search-tree chop