Создайте древовидную структуру из списка строковых путей

после тестирования вышеуказанных решений я нашел правильное.

(1) убедитесь, что переменные среды правильно установлены (M2_HOME = C: \ Program Files \ Apache Software Foundation \ apache-maven-3.3.3

M2 =% M2_HOME% \ bin) ( https://www.tutorialspoint.com/maven/maven_environment_setup.htm )

(2) откройте командную строку как администратор

(3) смените каталог на свое рабочее пространство (папка cd / workspace / project

(4) наконец (настроить)

архетип mvn: генерировать -DgroupId = fr.myGroupId -DartifactId = MyApplication -Dpackagename = fr.myGroupId -DarchetypeArtifactId = maven -archetype-quickstart.

19
задан Nativ 5 October 2018 в 11:42
поделиться

4 ответа

Следуйте реализации наивной реализации посещаемого дерева:

class Tree<T> implements Visitable<T> {

    // NB: LinkedHashSet preserves insertion order
    private final Set<Tree> children = new LinkedHashSet<Tree>();
    private final T data;

    Tree(T data) {
        this.data = data;
    }

    void accept(Visitor<T> visitor) {
        visitor.visitData(this, data);

        for (Tree child : children) {
            Visitor<T> childVisitor = visitor.visitTree(child);
            child.accept(childVisitor);
        }
    }

    Tree child(T data) {
        for (Tree child: children ) {
            if (child.data.equals(data)) {
                return child;
            }
        }

        return child(new Tree(data));
    }

    Tree child(Tree<T> child) {
        children.add(child);
        return child;
    }
}

интерфейсы для шаблона посетителя:

interface Visitor<T> {

    Visitor<T> visitTree(Tree<T> tree);

    void visitData(Tree<T> parent, T data);
}

interface Visitable<T> {

    void accept(Visitor<T> visitor);
}

образец реализации для шаблона посетителя:

class PrintIndentedVisitor implements Visitor<String> {

    private final int indent;

    PrintIndentedVisitor(int indent) {
        this.indent = indent;
    }

    Visitor<String> visitTree(Tree<String> tree) {
        return new IndentVisitor(indent + 2);
    }

    void visitData(Tree<String> parent, String data) {
        for (int i = 0; i < indent; i++) { // TODO: naive implementation
            System.out.print(" ");
        }

        System.out.println(data);
    }
}

и, наконец (!!!) простой тестовый пример:

    Tree<String> forest = new Tree<String>("forest");
    Tree<String> current = forest;

    for (String tree : Arrays.asList("x1/x2/x3", "x1/x2/x4", "x1/x5")) {
        Tree<String> root = current;

        for (String data : tree.split("/")) {
            current = current.child(data);
        }

        current = root;
    }

    forest.accept(new PrintIndentedVisitor(0));

вывод:

forest
  x1
    x2
      x3
      x4
    x5
32
ответ дан 30 November 2019 в 02:41
поделиться

Просто разделите каждый путь по его разделителю и затем добавьте их в древовидную структуру один за другим.
т.е. если 'x1' не существует, создайте этот узел, если он существует, перейдите к нему и проверьте, есть ли дочерний 'x2' и так далее ...

11
ответ дан 30 November 2019 в 02:41
поделиться

I'd make the tree one string at a time.

Make an empty tree (which has a root node - I assume there could be a path like "x7/x8/x9").

Take the first string, add x1 to the root node, then x2 to x1, then x3 to x2.

Take the second string, see that x1 and x2 are already there, add x4 to x2.

Do this for every path you have.

4
ответ дан 30 November 2019 в 02:41
поделиться

Create an Object Node which contains a parent (Node) and a List of children (Node).

First split the string using ",". For every splitted string you split the string using "/". Search for the first node identifier (e.g x1) in the root list. Если вы можете его найти, используйте этот узел, чтобы найти идентификатор следующего узла (например, x2).

Если вы не можете найти узел, добавьте его к последнему узлу, который вы смогли найти в существующих списках.

После того, как вы создали структуру списка, вы можете распечатать список на экране. Я бы сделал его рекурсивным.

НЕ ТЕСТИРОВАТЬ, просто анимация

public void print(List nodes, int deep) {
    if (nodes == null || nodes.isEmpty()) {
        return;
    }

    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < deep; i++) {
        buffer.append("---");
    }

    for (Iterator iterator = nodes.iterator(); iterator.hasNext();) {
        Node node = (Node)iterator.next();

        System.out.println(buffer.toString() + " " + node.getIdentifier());

        print(node.getChildren(), deep + 1);
    }
}
2
ответ дан 30 November 2019 в 02:41
поделиться
Другие вопросы по тегам:

Похожие вопросы: