【发布时间】:2016-10-11 07:01:22
【问题描述】:
我必须制作一个所谓的“命中平衡树”。不同之处在于,如您所见,我的节点类有一个名为 numberOfHits 的实例变量,每当您调用 contains 方法或 findNode 方法时,它都会递增。这个练习的重点是让命中数最高的节点位于顶部,因此树基本上会重建自身(或旋转)。 Root 显然具有最高的命中数。
我有一个关于我必须创建的方法的问题,该方法返回命中数最高的节点。稍后我将需要它来使树自行旋转(我想,至少这是计划)。这是我的节点类。 (当然是所有的吸气剂)
public class HBTNode<T> {
private HBTNode<T> left;
private HBTNode<T> right;
private T element;
private int numberOfHits;
public HBTNode(T element){
this.left = null;
this.right = null;
this.element = element;
this.numberOfHits = 0;
}
到目前为止,我所拥有的是:
public int findMaxCount(HBTNode<T> node) {
int max = node.getNumberOfHits();
if (node.getLeft() != null) {
max = Math.max(max, findMaxCount(node.getLeft()));
}
if (node.getRight() != null) {
max = Math.max(max, findMaxCount(node.getRight()));
}
return max;
}
这很好用,除了它返回一个整数。我需要返回节点本身。由于我必须递归地执行此操作,我决定找到最大的命中计数,然后在另一个返回节点的方法中使用此方法,就像这样(它可能真的效率低下,所以如果你有改进的提示,我在听) :
public int findMaxCount() {
return findMaxCount(root);
}
public HBTNode<T> findMaxCountNode(HBTNode<T> node) {
if (node.getNumberOfHits() == this.findMaxCount()) {
return node;
}
if (node.getLeft() != null ) {
return findMaxCountNode(node.getLeft());
}
if (node.getRight() != null) {
return findMaxCountNode(node.getRight());
}
return null;
}
我这样调用方法:
public HBTNode<T> findMaxCountNode() {
return findMaxCountNode(root);
}
即使我认为它应该没问题,它也会返回 null,我不擅长递归,所以很明显我错过了一些东西。如果你对我的这个练习有任何帮助,我愿意接受任何帮助,还有新的建议。非常感谢。
测试代码:
public static void main(String[] args) {
HBTree<Integer> tree = new HBTree<Integer>();
tree.add(50);
tree.add(25);
tree.add(74);
tree.add(19);
tree.add(8);
tree.add(6);
tree.add(57);
tree.add(108);
System.out.println(tree.contains(108)); //contains method increases the count by one
System.out.println(tree.contains(8));
System.out.println(tree.contains(8));
System.out.println(tree.contains(108));
System.out.println(tree.contains(8));
System.out.println(tree.contains(108));
System.out.println(tree.contains(108));
System.out.println(tree.contains(108));
System.out.println(tree.findMaxCountNode());
}
当前输出:true
true
true
true
true
true
true
true
null
预期输出:true
true
true
true
true
true
true
true
Element: 108
Left child: 6 //this is just a toString, doesn't matter at this point
Right child: null
Number of hits: 5
【问题讨论】:
-
欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布代码并准确描述问题之前,我们无法有效地帮助您。具体来说,出现问题的测试用例在哪里,也许还有一些跟踪输出?我们应该看到调试尝试的输出,即使只有几个策略性放置的 print 语句。
-
感谢您的耐心等待,我将对其进行编辑并发布输出。
标签: java recursion binary-search-tree