繁体   English   中英

递归查找二叉树中节点的路径

[英]Recursively finding the path to a node in a Binary Tree

我知道要搜索的节点在未排序的二叉树中,但是我不知道如何通过递归调用将路径传递回去。 我的两个功能:一个找到到特定节点的路径,另一个返回到所有节点的路径字符串。 0表示采用了左路径,而1表示采用了右路径。

private static String getAllPaths(final BinaryNodeInterface<Character> root)
{
    // TO DO
    String path = "";
    String returnStr = "";
    return getAP(root, path, returnStr);
}

private static String getAP(BinaryNodeInterface<Character> root, String path,
        String returnStr) 
{
    returnStr += "" + root.getData() + " " + path + "\n";
    if(root.hasLeftChild())
        getAP( root.getLeftChild(), path.concat("0"), returnStr);
    if(root.hasRightChild())
        getAP( root.getRightChild(), path.concat("1"), returnStr);

    return returnStr;
}

private static String getPathTo(final BinaryNodeInterface<Character> root, char c)
{
    // TO DO
    String path = "";
    if( root.getData() == c )
        return path;

    if( root.hasLeftChild() )
    {
        String s = getPathTo(root.getLeftChild(), c);

        if( s != null )
        {
            path += "0";
            path += s;
            return path;
        }
    }

    if( root.hasRightChild() )
    {
        String s = getPathTo(root.getRightChild(), c);

        if( s != null )
        {
            path += "1";
            path += s;
            return path;
        }
    }

    return null;
}

我在递归方面很糟糕,因此对您的任何帮助都深表感谢。 我全都工作了。 上面的代码现在很好。 谢谢您的帮助。

字符串在Java中是不可变的。 当您将String传递给方法时,将创建一个全新的值。 例如:

void modifyString(String x) {
    x += "(modified)";
}

如果使用该方法:

String s = "myString!";
modifyString(s);
// what does s equal?

您可能期望s == "myString!(modified)" ,但这不是事实。

在您的情况下,您returnStr作为参数传递给对getAP递归调用。 但是,它不会像您假设的那样被修改。 要解决此问题,请将递归方法调用的结果附加到本地returnStr并返回。

// removed returnStr as a parameter
private static String getAP(BinaryNodeInterface<Character> root, String path) 
{
    String returnStr = "" + root.getData() + " " + path + "\n";
    if(root.hasLeftChild())
        returnStr += getAP( root.getLeftChild(), path.concat("0")); 
    if(root.hasRightChild())
        returnStr += getAP( root.getRightChild(), path.concat("1"));

    return returnStr;
}

我瞥了一眼您的getPT方法,实际上看不到任何明显的问题。

暂无
暂无

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

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