到目前为止,我已经发现了http://pastebin.com/gXJVXdLS
5
。创建一个删除方法。如果找到该项目,则搜索树,然后将其杀死。然后你必须以AVL方式平衡树,以正确填充你所做的洞。再次,使用维基百科描述(这是非常好的)以及模拟器,甚至可能是我的讲座,以使删除工作正常。我不会提供关于这个的样本数据 - 你现在可以自己解决这个问题。请记住,除了一般情况外,您还有两个需要双重旋转的特殊情况(有关左/右或右/左情况的情况,请参阅讲座或使用模拟器进行演示。)
现在我需要实现这个功能
public void remove(K输入)
帮助我。我做了这个
public void remove(K input) {
root = remove(root,input);
}
public AVLNode<K> remove(K x, AVLNode<K> t) {
if (t==null) {
System.out.println("Sorry but you're mistaken, " + t + " doesn't exist in this tree :)/>\n");
return null;
}
System.out.println("Remove starts... " + t.data + " and " + x);
if (x.compareTo(t.data) < 0 ) {
t.left = remove(x,t.left);
int l = t.left != null ? getHeight(t.left) : 0;
if((t.right != null) && (getHeight(t.right) - l >= 2)) {
int rightHeight = t.right.right != null ? getHeight(t.right.right) : 0;
int leftHeight = t.right.left != null ? getHeight(t.right.left) : 0;
if(rightHeight >= leftHeight)
t = rotateLeft(t);
else
t = rotateRight(t);//double
}
}
else if (x.compareTo(t.data) > 0) {
t.right = remove(x,t.right);
int r = t.right != null ? getHeight(t.right) : 0;
if((t.left != null) && getHeight(t.left) - r >= 2) {
int leftHeight = t.left.left != null ? getHeight(t.left.left) : 0;
int rightHeight = t.left.right != null ? getHeight(t.left.right) : 0;
if(leftHeight >= rightHeight)
t = rotateRight(t);
else
t = rotateLeft(t);//and double
}
}
return t;
} //End of remove...
答案 0 :(得分:0)
nvm找到了答案
private AVLNode<K> findMin( AVLNode<K> t )
{
if( t == null )
return t;
while( t.left != null )
t = t.left;
return t;
}
public void remove( K x )
{
root = remove( x, root );
}
private AVLNode<K> remove( K x, AVLNode<K> t )
{
if( t == null )
return t; // Item not found; do nothing
int compareResult = x.compareTo( t.data );
if( compareResult < 0 )
t.left = remove( x, t.left );
else if( compareResult > 0 )
t.right = remove( x, t.right );
else if( t.left != null && t.right != null ) // Two children
{
t.data = findMin( t.right ).data;
t.right = remove( t.data, t.right );
}
else
t = ( t.left != null ) ? t.left : t.right;
return t;
}