Я хочу сгенерировать дерево из массива (например, String), но я не знаю, как это сделать.java - Как сгенерировать дерево из двумерного массива
Мой входной массив:
[a, f, d, s]
[a, f, w]
[b, r]
[a, p]
[b, n, l]
Я хочу, чтобы дерево, как это:
Root
b
r
n
l
a
f
w
d
s
p
Это мой код до сих пор:
public class TreeGenerator {
public TreeGenerator(E root, E[][] array){
List list = Arrays.asList(array);//makes list
Set set = new HashSet(list);//then set
Node tree = new Node(root, set, 0);//makes whole tree
System.out.println(tree.toString());//displays tree
}
public static void main(String[] args) {
String[][] array = new String[][] { { "a", "f", "d", "s" }, { "a", "f", "w" }, { "b", "r" }, { "a", "p" }, { "b", "n", "l" } };
for(String[] s : array){
System.out.println(Arrays.toString(s));
}
new TreeGenerator("Root", array);
}
}
public class Node {
private final E nodeName;
private final Node[] children;
private final int depth;
/**
* Constructs a Node and its children.
*
* @param name Node name
* @param array Set of arrays
* @param depth Index of arrays
*/
public Node(E name, Set array, int depth) {
nodeName = name;
this.depth = depth;
Map map = new HashMap();
for (E[] line : array) { //iterates over arrays
if (line.length > depth) { //checks if an element exists at this depth
E common = line[depth]; //gets an element
Set branch = map.get(common); //gets a branch for the element
if (branch == null) { //if first such an element
branch = new HashSet(); //creates branch
map.put(common, branch); //adds for the element
}
branch.add(line); //adds the line for proper branch
}
}
children = new Node[map.size()];
int i = 0;
depth++;//gets deeper
for (Map.Entry entry : map.entrySet()) {//iterates over map
children[i] = new Node(entry.getKey(), entry.getValue(), depth);//makes child
i++;
}
}
}
Я не вижу, как этот 2d-массив преобразуется в дерево. –
Дерево, которое вы пытаетесь реализовать, представляет собой структуру данных с именем Trie, просто Google. – user3707125