好的,我想要一个二元搜索树来平衡,我知道为什么它不起作用,但我不知道如何解决它.这就是我的平衡方法.
public void balance(){
if(isEmpty()){
System.out.println("Empty Tree");
return;
}
if(!isEmpty()){
values = new Object[count()];
index = 0;
createAscendingArray(root);
clear();
balanceRecursive(0, index);
values = null;
}
}
private void createAscendingArray(TreeNode<E> current){
if(current == null)
return;
if(current.getLeftNode() != null)
createAscendingArray(current.getLeftNode());
else if(current.getRightNode() != null)
createAscendingArray(current.getRightNode());
values[index] = current.getData();
index++;
}
private void balanceRecursive(int low, int high){
if(low == high)
return;
else if(low > high/2)
balanceRecursive(high/2, high);
else if(low < high/2)
balanceRecursive(low, high/2);
E insert = (E) values[(low + high)/2];
insertItem(insert);
}
Run Code Online (Sandbox Code Playgroud)
为了增加一些清晰度,index是预定义的私有int变量,values也是预定义的Object …