【发布时间】:2012-04-09 17:48:22
【问题描述】:
我正在构建一个递归 Java 方法,以使用每个节点中的权重来平衡二叉搜索树(使用整数,但设计为通用)。就我而言,节点的权重定义为子节点数 + 1。
2
/ \
1 3
The weight of the root is 3, and the weight of both leaves is 1.
在平衡结束时,任何节点的值应该是以该节点为根的子树中所有节点的值的中值。
这是我的代码:
public void weightBalance (BinarySearchTree<AnyType> t) {
// Base case
if (t.getRoot().left == null && t.getRoot().right == null) {
return;
}
// Get median of tree
AnyType median = t.getMedian();
// Create new BST with median as root
BinarySearchTree<AnyType> newTree = new BinarySearchTree<AnyType>();
newTree.insert(median);
// Insert all values except median into new BST
ArrayList<AnyType> stack = new ArrayList<AnyType>();
inorderTraverse(t.getRoot(), stack);
Iterator<AnyType> itr = stack.iterator();
while (itr.hasNext()) {
AnyType temp = itr.next();
if (temp != median) { // Comparing values or reference?
newTree.insert(temp);
}
}
// Replace old BST with new BST
t = newTree; // t is a copy of the reference, is this the problem?
// Recurse through children
// Tree constructor for reference:
// public BinarySearchTree (BinaryNode<AnyType> t) {
// root = t;
// }
if (t.getRoot().left != null) {
weightBalance(new BinarySearchTree(t.getRoot().left));
}
if (t.getRoot().right != null) {
weightBalance(new BinarySearchTree(t.getRoot().right));
}
}
我正在尝试修改树而不返回任何内容,但代码不会更改树。我知道我通过引用传递和某处的值传递搞砸了,但我不知道在哪里 - 任何人都可以帮忙吗?我花了几个小时调试,但在调试递归时我真的很困惑。
【问题讨论】:
-
查看有关 AVL 树的相关问题,stackoverflow.com/questions/5771827/…
标签: java recursion binary-search-tree recursive-datastructures tree-balancing