【问题标题】:Recursive Traverse of Binary Tree Not Terminating At Return Statement二叉树的递归遍历未在返回语句处终止
【发布时间】: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


    【解决方案1】:

    您在 else 块中的调用不会返回 - 它们可能应该像这样:

    if (tree.getLeftSubtree() != null) {
       // Traverse the left side, add a DOT to the end of a string to
       // change the morse code
       return 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
        return encode(tree.getRightSubtree(), target, s + DASH);
    }
    

    但是,如果左右子树都为空,你想发生什么?如果它们都是非空,你想返回什么?

    请注意,仅仅因为您的基本调用已经返回,它只会返回 该单个调用 - 而不是堆栈中的所有其他调用。递归不会替换堆栈帧与新调用 - 它只是添加另一个堆栈帧1。从那个新的堆栈帧返回只会让你回到原来的位置。


    1 是的,我知道尾递归。不过,我们不要混淆。

    【讨论】:

    • 我希望它返回的是目标字符的莫尔斯电码。我正在构建一个字符串,该字符串在递归的每个步骤中用 s 和 DOT 或 DASH 表示该代码。虽然我认为当我返回时递归会停止。我猜不是。
    • 好吧,看来我确实需要 else 块中的 return 语句,但我在那里的某个地方做了其他错误,因为它没有超出我的左侧遍历。我需要稍微跟踪一下我的代码,看看我哪里出错了,尽管你关于添加 return 语句的提示似乎为我指明了正确的方向。
    • @Penn:当你从第一个方法调用返回时它会停止——当你已经向下 10 个堆栈帧时的 return 语句不会一直向上弹出堆栈。
    猜你喜欢
    • 1970-01-01
    • 2019-08-23
    • 1970-01-01
    • 1970-01-01
    • 2013-07-23
    • 2016-05-01
    • 1970-01-01
    • 2010-11-20
    相关资源
    最近更新 更多