我必须为AVL树实现一个有序迭代器。为此,我将所有节点(使用有序遍历)存储在ArrayList中。我可以使用这个ArrayList和一个计数器变量很容易地使用hasNext()和next()方法。但我不知道如何实现remove()方法。如果我删除某些东西,底层AVL树有可能会自我平衡,这将抛出排序错误...这会弄乱迭代器的hasNext()和next()方法。我错过了什么?任何帮助将不胜感激。
private ArrayList <E> recInOrderToArrayList (AVL_Node <E> node, ArrayList<E> inOrderList){
if (node == null){
return inOrderList;
}
else{
recInOrderToArrayList (node.getLeft(), inOrderList);
inOrderList.add(node.getData());
recInOrderToArrayList (node.getRight(), inOrderList);
}
return inOrderList;
}
public ArrayList <E> inOrderToArrayList (){
ArrayList<E> inOrderList = new ArrayList <E> ();
return recInOrderToArrayList (root, inOrderList);
}
private class AVL_inOrder_Iterator implements Iterator <E>{
private AVL_Node <E> current;
private int current_num = 0;
private ArrayList <E> inOrderList_2;
private int size;
public AVL_inOrder_Iterator (){
this.current = root;
if (root!= null){
//store all nodes in ArrayList w/ inOrder Traversal
inOrderList_2 = inOrderToArrayList();
size = inOrderList_2.size();
}
}
public boolean hasNext (){
if (current_num > size) return true;
else return false;
}
public E next(){
if (!hasNext()) {
throw new NoSuchElementException();
}
else {
E data = inOrderList_2.get(current_num);
current_num ++;
return data;
}
}