繁体   English   中英

二叉树的递归遍历不终止于返回语句

[英]Recursive Traverse of Binary Tree Not Terminating At Return Statement

我创建了一个用莫尔斯电码填充二叉树的类。 向左遍历表示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;
    }

您在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);
}

但是,如果左子树和右子树都为空,您想发生什么? 如果它们都不为null ,您想返回什么?

请注意,仅因为您的基本调用已经返回,才针对该单个调用返回-而不是堆栈中的所有其他调用。 递归不会用新的调用替换堆栈框架,而只是添加另一个堆栈框架1 从新的堆栈框架返回就可以让您回到原来的状态。


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM