我需要使用inorder遍历输出来平衡正常的BST。这个想法非常简单:查找列表的平均值,并为所有旁注列表递归执行相同的操作。这会一次添加每个级别的节点,理论上应该会生成一个新的平衡树。但是,我似乎无法让代码完全正确。谁能给我一个关于我哪里出错的提示?
public void simpleBalance() {
if (this.isEmpty()){
return;
}
balancedTree = new Tree();
balanceHelper((this.size() - 1) / 2);
balanceHelper(this.size() - 1);
this.root = balancedTree.root;
}
public void balanceHelper(int k){
if (balancedTree.size() == this.size()){
return;
}
if((k/2) >= this.size()){
return;
}
if (k == 1){
balancedTree.insert(valueAtPosition(0));
}
balancedTree.insert(valueAtPosition((k/2)));
balanceHelper((k - 1) * 2);
balanceHelper((k + 1) * 2);
}
完整代码:
Output:
Height old tree:
9
Root old tree:
1
Old traversal:
1,2,3,4,5,6,7,8,9,10,
New traversal
3,4,5,6,8,9,10,
Height new tree:
5
Root new tree:
3