在java中以字符串形式打印树

chhkpiq4  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(307)

这段代码需要打印一棵树,但我需要生成一个精确打印的字符串。所以函数将是字符串而不是空的。我用syso举例说明我的结果。它必须是递归的。这个节点有一个inf,左,右。函数 visualitza() 打印卡片。我还创建了一个函数 VisualitzaStr 以字符串形式返回卡片。

代码:

private void print2DUtil(NodeA root, int space, String dir) {
        // Base case
        if (root == null){
            return;
        }

        space += COUNT;
        for (int i = COUNT; i < space; i++)System.out.print(" ");
        Carta aux = root.inf;
        if (root.drt != null && root.esq != null) {
            if (root.drt.inf == null && root.esq.inf == null) {
                root.drt = null;
                root.esq = null;
            }
        }
        if (aux == null){
            System.out.println("No té fill" + dir+"\n");
        }

        else {
            aux.visualitza();
            System.out.println();
        }
        print2DUtil(root.drt, space, " Dreta");
        print2DUtil(root.esq, space, " Esquerra");
        return ;
    }

    // Wrapper over print2DUtil()
    public void print2D() {
        String str = "";
        // Pass initial space count as 0
        print2DUtil(this.arrel, 0, "");
    }
}

代码中的示例:

AS de COPES 
          SET de BASTONS    
                    SIS de COPES    
                              SIS de ESPASES    
                              AS de OROS    
                    AS de ESPASES   
                              CINC de OROS  
                              TRES de COPES 
          SET de COPES  
                    QUATRE de OROS  
                              AS de BASTONS 
                              CINC de COPES 
                    TRES de BASTONS 
                              DOS de COPES  
                              CABALL de OROS
8dtrkrch

8dtrkrch1#

在这里,使用printwriter而不是system.out是最简单的。这不能再是一个全局变量(如system.out),但必须是一个额外的参数。

print2DUtil(root, space, dir, new PrintWriter(System.out));

StringWriter sw = new StringWriter(),
try (PrintWriter out = new PrintWriter(sw)) {
    print2DUtil(root, space, dir, out);
}
String Sr sw.toString();

private void print2DUtil(NodeA root, int space, String dir, PrintWriter out) {
    ... out instead of System.out

相关问题