【发布时间】:2020-11-16 21:05:27
【问题描述】:
这段代码打印了一个想要的树,但我需要用精确的打印来制作一个字符串。所以函数将是字符串并且没有void。我用 SYSO 举例说明了我的结果。它必须是递归的。该节点有一个inf,left,right。函数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
【问题讨论】: