从字符串路径列表构造树结构 [英] Construct a tree structure from list of string paths
问题描述
我在列表中有一串字符串路径,如[x1 / x2 / x3,x1 / x2 / x4,x1 / x5]。
我需要从这个列表中构造一个树状结构,可以迭代得到一个漂亮的打印树。
喜欢这个
I have a collection of string paths like ["x1/x2/x3","x1/x2/x4","x1/x5"] in a list. I need to construct a tree-like structure from this list which can be iterated to get a pretty printed tree. like this
x1
/ \
x5 x2
/ \
x3 x4
任何想法/建议?
我相信通过处理字符串列表可以首先攻击问题EDIT:选择的正确答案是优雅的实现,其他建议也很好。
Any ideas/suggestions? I believe that the problem can be attacked first by processing the list of strings The correct answer chosen was an elegant implementation, other suggestions were good too.
推荐答案
按照实现可访问树的天真实现:
Follow an implementation of naive implementation of a visitable tree:
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);
}
}
最后(!!!)一个简单的测试案例:
and finally (!!!) a simple test case:
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
这篇关于从字符串路径列表构造树结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!