java - 如何在控制台中打印通用树?
问题描述
我一直在尝试使用Node
下面的此类在控制台中打印出格式正确的通用树。我通常会展示我的尝试,但我什至不知道从哪里开始。任何人都可以给我一些关于如何解决这个问题的指示吗?
class Node{
public String letter;
public Node parent;
public Map<String, Node> connections = new LinkedHashMap<String, Node>();
public Node(String letter, Node parent){
this.letter = letter;
this.parent = parent;
}
public int getChildrenCount(){ return connections.size(); }
public ArrayList<Node> getChildren(){
ArrayList<Node> out = new ArrayList<Node>();
for(Node node : connections.values()){
out.add(node);
}
return out;
}
public String toString(){ return letter; }
}
我希望输出看起来像这样,例如:
|--j
|
| |--c
a--b
| |--d
|
| |--g
| |--f
|--e
|--h
|--i
解决方案
您尝试做的事情是可能的,但很难智能地实现,因为它需要做出间距决定以避免重叠。解密树的一个简单的解决方案是:
public String toString() {
String s = letter + "(";
for (Node n : connections.keySet()) {
s += n.toString() + ",";
}
return s + ")";
}
如果你需要它格式化你如何显示(编辑):
HashMap<String, ArrayList<String>> map;
public String toString() {
findAsString();
ArrayList<String> lines = map.get(this.letter);
for (String l : lines) {
System.out.println(l);
}
}
public String findAsString() {
map = new HashMap<>();
for (Node n : connections.keySet()) {
findAsString(n);
}
ArrayList<String> lines = new ArrayList<>();
for (Node n : connections.keySet()) {
ArrayList<String> nodeLines = map.get(n.letter);
for (String s : nodeLines) {
// CONFIGURE THIS PREFIX to include the letter itself, and needed lines
String prefix = "| ";
lines.add(prefix + s);
}
lines.add("");
}
if (nodeLines.size() == 0) {
lines.add("|--" + this.letter);
}
map.put(this.letter, lines);
}
推荐阅读
- amazon-web-services - 如何从cloudwatch查看日志流属于哪个ECS服务或任务?
- python - 无法为 Zipline 安装 Python 3.5 文件
- python - 来自excel报告的Python dict
- angular - Angular 的文档管理系统
- html - 在NodeJS中获取玉选择框值
- git - 如何为 VSTS 添加 GIT 子模块以用于 Visual Studio 2017
- php - 如何修复我的脚本:更新用户通行证(php mysql)(没有错误但有些东西不起作用)
- python - 使用 Datashader / Holoviews / Bokeh 循环子图
- c - 在 Swift 中使用类型时如何排除 C 枚举案例
- css - 缓存的 CSS 文件将在浏览器中更新多长时间?