0

我需要打印出四叉树。问题是我不知道如何实现递增移位以便能够可视化树结构。目前我只是在一个新行上看到每个级别的节点。但是,使用这种可视化来处理树是很复杂的。

         @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();
         }
4

1 回答 1

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();
    }


}
于 2013-10-24T15:22:54.500 回答