更新11:15 pm est 4/29/15 -
谢谢你帮助了很多人,几乎就在那里......
public BinarySearchTree<AnyType> rebalanceHelp(ArrayList<AnyType> nl){
BinarySearchTree<AnyType> p = new BinarySearchTree<AnyType>();
//base case, if theres two elements in the list,
if(nl.size() == 2){p.insert(nl.get(0));p.insert(nl.get(1));}
ArrayList<AnyType> left = new ArrayList<AnyType>();
ArrayList<AnyType> right = new ArrayList<AnyType>();
p.insert(nl.get(nl.size()/2));
//loops through first half of the arraylist putting each element into a new arraylist, left
for(int i = 1; i < ((nl.size()/2)-1); i++){
left.add(nl.get(i));
}
//loops through second half of the arraylist putting each element into a new arraylist, right
for(int j = nl.size()-1; j > ((nl.size()/2)+1); j--){
right.add(nl.get(j));
}
//recursivley calls on left and right
rebalanceHelp(left);rebalanceHelp(right);
return p;
}
public void rebalance(){
//need a list of some sort (l) that i can resize and add to even if it is full
ArrayList<AnyType> l = new ArrayList<AnyType>();
//ArrayList<AnyType> nl = new ArrayList<AnyType>();
while(this.isEmpty() != true){
l.add(this.findMin());
this.removeMin();
}
this.rebalanceHelp(l);
}
现在收到错误:
DuplicateItemException: 8
at BinarySearchTree.insert(BinarySearchTree.java:171)
at BinarySearchTree.insert(BinarySearchTree.java:169)
at BinarySearchTree.insert(BinarySearchTree.java:78)
at BinarySearchTree.rebalanceHelp(BinarySearchTree.java:46)
at BinarySearchTree.rebalanceHelp(BinarySearchTree.java:58)
at BinarySearchTree.rebalanceHelp(BinarySearchTree.java:58)
at BinarySearchTree.rebalanceHelp(BinarySearchTree.java:58)
at BinarySearchTree.rebalance(BinarySearchTree.java:73)
at BinarySearchTree.main(BinarySearchTree.java:337)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
问题在于我的递归方法中的for循环,对这些问题的任何帮助都会很棒,最后几个答案给了我很多洞察和理解。 谢谢,亚光
答案 0 :(得分:0)
这不是您通常如何平衡BST。当BST不平衡时,您可以通过旋转节点来修复它。这是一个代码来处理它的链接。 http://users.cis.fiu.edu/~weiss/dsaajava3/code/AvlTree.java