繁体   English   中英

如何获得从根到任意树上给定节点的路径?

[英]How to get the path from root to a given node on a arbitrary tree?

我有这棵树:

Harry(root)
Jane
    Joe
    Diane
        George
            Jill
                Carol
        Mary
    Mark
Bill
    Grace

我已经在此页面中扩展了代码

具有使用深度优先搜索的功能

public static int path(Tree t, String root, String n)
{
    // Default traversal strategy is 'depth-first'
    int counter = 0;
    Iterator<Node> depthIterator = t.iterator(root);
    while (depthIterator.hasNext()) {
        Node node = depthIterator.next();
        if(node.getIdentifier().compareTo(n)==0)
        {
            System.out.println("Distance from " + root +" to " + n + " " + counter);
            return counter;
        }
        counter++;
        System.out.println(node.getIdentifier());
    }
    return 0;
}

我的最终目标是找到根与给定节点之间的路径长度。 当我运行此函数时,与根和Joe的距离以及与根和Diane(它们的兄弟姐妹)的距离是不同的,因为它计算深度优先搜索的步骤。 这种方法是错误的还是解决方法?

您使用计数器查找深度不正确。 在显示的代码中,您仅在迭代器中计算项目。

您需要递归调用path()方法,并将depth值作为该方法的参数传递。 并为每个递归调用增加深度值。

暂无
暂无

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

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