【发布时间】:2011-12-08 11:09:11
【问题描述】:
我创建了一个用莫尔斯电码填充二叉树的类。向左移动表示 DOT,向右移动表示 DASH。一切都很顺利,直到我编写了一个将字母字符转换为莫尔斯电码字符串的编码方法。该方法应递归地执行树的前序遍历(沿途创建莫尔斯电码字符串),直到找到目标字符然后返回该字符串。
但是,由于某种原因,我的递归不会在我的基本情况下终止。它只是继续运行整个遍历。我附上了下面方法的代码。为什么if语句中的return语句没有触发并结束方法?
对不起,如果这含糊不清,但我不想为我的整个项目发布 300 行代码,因为比我更聪明的人会立即注意到问题。
感谢您的帮助
//wrapper class
//@parameter character is the character to be encoded
//@return return the morse code as a string corresponding to the character
public String encode(char character){
return encode(morseTree, character, "");
}
//@Parameters tree is the binary tree is the tree to be searched,
//element is the target character trying to be foudn, s is the string being used to build the morse code
//@return returns the morse code that corresponds to the element being checked
public String encode(BinaryTree<Character> tree, char target, String s){
if(tree.getData() == target){ //if the data at the current tree is equal to the target element
//return the string that is holding the morse code pattern for this current traversal
return s;
}else{
if(tree.getLeftSubtree() != null){
//Traverse the left side, add a DOT to the end of a string to change the morse code
encode(tree.getLeftSubtree(), target, s + DOT);
}
if(tree.getRightSubtree() != null){
//Traverse the left side, add a DOT to the end of a string to change the morse code
encode(tree.getRightSubtree(), target, s + DASH);
}
}
//The code should never get this far!
return s;
}
【问题讨论】:
标签: java recursion binary-tree