我需要打印出QuadTree。问题是我不知道如何实现递增移位以便能够可视化树结构。 目前我只看到新线路上的每个级别的节点。但是,使用此可视化来处理树是很复杂的。
@Override public String toString() {
StringBuilder result = new StringBuilder();
String NEW_LINE = System.getProperty("line.separator");
String SHIFT = System.getProperty(" ");
if (_children != null) {
String content = "";
for (QtreeNode<E> node : _children) {
content += node.toString() + ",";
}
result.append("{" + SHIFT + NEW_LINE +
content.substring(0, content.length()) +
SHIFT + NEW_LINE + "}");
} else if (_items != null) {
String content = "";
for (E item : _items) {
content += item.toString() + " ";
}
result.append("[" + content + "]");
}
return result.toString();
}
答案 0 :(得分:1)
为树节点提供单独的toStringWithIndent(int depth)方法,并在内部调用toString()。该方法将递归地为每个子节点等调用相同的方法。
UPD一些例子
class Node {
private String name;
private List<Node> children;
@Override
public String toString() {
String s = name;
for(Node n: children) s += children.toStringWithIndent(1);
return s;
}
private String toStringWithIndent(int depth) {
// same as toString() but with indent
String s = indentFor(depth) + name;
for(Node n: children) s += indentFor(depth) +
children.toStringWithDepth(depth + 1);
return s;
}
private static String indentFor(int depth) {
StringBuilder b = new StringBuilder(depth);
while(depth-- > 0) {
b.append(" ");
}
return b.toString();
}
}