【问题标题】:Showing the whole path of every Leaf in a Tree显示树中每片叶子的完整路径
【发布时间】:2014-03-18 19:28:53
【问题描述】:

我给自己写了一个快速的树和节点类(没什么花哨的,不需要做太多)。 我有可变数量的下一级节点,我使用 ArrayList 来处理这些节点。 它按预期工作,唯一的问题是 toString() 方法。 示例:我用一堆数字设置它。

  • 0 是根
  • 0 有孩子 1,2,3
  • 2 有 2.4 和 2.5 的孩子

现在,当我打印出树时,我得到的是:(应该有斜线)

  • /0/1
  • /2/2.5
  • /2.4
  • /3

我想要的是这样的:

  • /0/1
  • /0/2/2.5
  • /0/2/2.4
  • /0/3

这是我的 toString() :

public String toString() {
    String all = "";
    for (Node<T> node : nextNodes) {
        all += node.toString();
        if (node.isLeaf()) {
            all += "\n";
        }
    }
    return "/" + this.getNodeContent().toString() + all;
}

有人能告诉我我必须改变什么才能每次都从根开始吗?谢谢!

【问题讨论】:

标签: java path tree nodes directory-walk


【解决方案1】:

三者中有多少条路径?路径与叶子一样多 - 因为您的代码不起作用。 您编写的代码仅遍历所有节点。 但是你想打印从根到叶子的所有路径。

一种解决方案是使用递归: 它从每个孩子的根目录和打印路径开始。 它看起来像这样

public void printPaths(Node<T> nodeOnPath, String onPath){
    String nodePath = onPath + "/" + nodeOnPath.getNodeContent().toString(); 
    if (nodeOnPath.isLeaf()){
        System.out.println(nodePath);
        return; 
    }

    ArrayList<Node> children = nodeOnPath.getChildren(); 
    for (Node<T> node : children){
        printPaths(node, nodePath); 
    }
}

打印路径的方法我命名为 printPaths - 它有两个参数:第一个是节点 nodeOnPath,第二个是从根到节点 nodeOnPath 的路径。 在方法的第一行,它创建了 nodePath。 然后检查节点是否为叶子 - 如果答案是肯定的,则打印 nodePath 并退出该方法。

如果节点不是叶子,则获取该节点的所有子节点,遍历它们并为每个节点生成路径。这部分在每个循环中。

要打印所有路径,您将像这样调用方法 printPaths

printPaths(rootNode, "");

【讨论】:

    【解决方案2】:

    您需要将 getNodeContent() 添加到每个子路径,这是一个解决方案:

       public String toString() {
            String all = ""
            for (Node<T> node : nextNodes) {
                all += this.getNodeContent().toString() + node.toString();
                if (node.isLeaf()) {
                    all += "\n";
                }
            }
            return "/" +  + all;
        }
    

    【讨论】:

      猜你喜欢
      • 2022-01-26
      • 2022-11-20
      • 2013-01-03
      • 2013-02-26
      • 2016-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多