【发布时间】:2014-03-17 13:00:25
【问题描述】:
我正在使用 Java 实现 Shannon/Fano 算法,我通过计算文本文件中符号的频率来做到这一点,然后我将所有这些值放在树中。问题是,当我在树中搜索某个符号时,我还必须更新相应符号的代码(例如,如果我向左追加 0,否则为 1)并递归地执行此操作,我得到一个 stackoverflow 错误。以下是我的代码:
private String getNodeValue(Node node, String symbol) {
if (node.getLeftChild() != null) {
if (node.getLeftChild().getData().equalsIgnoreCase(symbol)) {
node.updateCode(0);
return node.getData() + "";
}
} else if (node.getRightChild() != null) {
if (node.getRightChild().getData().equalsIgnoreCase(symbol)) {
node.updateCode(1);
return node.getData() + "";
}
}
Node nextLeftNode = node.getLeftChild().getLeftChild();
if (nextLeftNode != null) {
getNodeValue(nextLeftNode, symbol);
}
Node nextRightNode = node.getRightChild().getRightChild();
if (nextRightNode != null) {
getNodeValue(nextRightNode, symbol);
}
// if symbol is not found return null
return null;
}
当调用 node.getData() 时,stackoverflow 错误会在方法的第一行触发。这是我的堆栈跟踪:
Exception in thread "main" java.lang.StackOverflowError
at ro.uvt.it.datastractures.Node.getData(Node.java:47)
at ro.uvt.it.datastractures.Node.getData(Node.java:47)
at ro.uvt.it.datastractures.Node.getData(Node.java:47)
这是我的 getData() 方法:
public String getData() {
return this.getData();
}
任何帮助或提示将不胜感激, 谢谢。
【问题讨论】:
-
.getData()是做什么的?您可能在某个地方处于非常深的循环或无限循环中。 -
.getData() 只是一个获取数据属性的 getter 方法,它是一个字符串。我不知道...奇怪的是,如果我使用调试器,异常会在第一行引发,因此不会到达递归调用。
-
在 .getData() 函数中设置断点会发生什么?
-
在我看来,您的第二个 if 语句
if (((String) node.getData()).equalsIgnoreCase(symbol))与第一个if (node.getData().equalsIgnoreCase(symbol))完全相同。你在这两种情况下都使用node.getData(),因为它已经返回了一个字符串,所以在第二个 if 语句中再次将它转换为一个字符串不会有什么不同。 -
正如@OMGtechy 所暗示的,递归在
getData方法中,而不是在getNodeValue方法中,所以你在这里发布了错误的方法。
标签: java tree recursive-datastructures