我正在进行此AVLTree分配,我遇到了insert方法的问题。当它到达z.resetHeight();
时,我收到一个错误 public void insert(K key, V value) {
AVLnode<K, V> hold = TreeSearch(key, root);
AVLnode<K, V> z = hold;
DictEntry<K, V> temp = new DictEntry<K, V>(key, value);
z.setEntry(temp);
while (z != null) {
z.resetHeight();
if (java.lang.Math
.abs(z.left().getHeight() - z.right().getHeight()) > 1) {
z = triNodeRestructure(z.parent().parent(), z.parent(), z);
z.left().resetHeight();
z.right().resetHeight();
z.resetHeight();
break;
}
size++;
z = z.parent();
}
}
resetHeight来自AVLnode类,我不允许按照赋值中的规定进行修改。
public class AVLnode<K,V> implements Position<K,V> {
private AVLnode<K,V> parent; // reference to the parent node
private AVLnode<K,V> left; // reference to the left child
private AVLnode<K,V> right; // reference to the right child
private DictEntry<K,V> entry; // reference to the entry stored at the node
private int height; // height of the node for checking balance-height property
public AVLnode(DictEntry<K,V> inputEntry, AVLnode<K,V> inputParent, AVLnode<K,V> inputLeft, AVLnode<K,V> inputRight)
{
entry = inputEntry;
parent = inputParent;
left = inputLeft;
right = inputRight;
height = 0;
if (left != null ) height = Math.max(height,1+left.getHeight());
if (right != null ) height = Math.max(height,1+right.getHeight());
}
public AVLnode<K,V> parent(){ return parent;}
public AVLnode<K,V> left() {return left;}
public AVLnode<K,V> right() {return right;}
public int getHeight () { return height; }
public DictEntry<K,V> getEntry() { return entry; }
public void setParent(AVLnode<K,V> newParent){ parent = newParent; }
public void setLeft(AVLnode<K,V> newLeft) {left = newLeft;}
public void setRight(AVLnode<K,V> newRight) { right = newRight; }
public void setEntry(DictEntry<K,V> newEntry) { entry = newEntry; }
public DictEntry<K,V> element(){return entry;}
public void resetHeight() throws AVLTreeException{
if ( left == null || right == null ) throw new AVLTreeException("Attempt to update height for external node ");
height = 1+Math.max(left.getHeight(),right.getHeight());
}
}
我认为问题在于,当我使用我的插入方法时,我还没有设置一个左或右孩子。因此getHeight会抛出异常,因为我插入的节点的两个子节点都是null。我不太确定如何实现这一点。我已经尝试创建新节点来设置为hold和左右孩子,但我不知道我应该把什么作为参数而不会弄乱列表除了null,但这只会让我回到哪里我是。
答案 0 :(得分:0)
由于z
没有任何子女,因此不能失衡,请从resetHeight()
的父级开始z
循环:
z.setEntry(temp);
z = z.parent();
while (z != null) {
z.resetHeight();
// etc...