java中带逗号的顺序遍历递归打印

webghufk  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(291)

我试图在java中打印一个二叉树的有序遍历实现。我上了以下两门课:

public class Tree {

  private TreeNode root; // root of the tree, vantage point

}

以及

public class TreeNode {

  private TreeNode left; // left successor of current node

  private TreeNode right; // right successor of current node

  private final int value; // value stored in the current node

}

(对于这两个类,已经实现了insert方法)
现在我正在尝试为treenode类实现一个tostring方法,以实现有序遍历并将其作为字符串返回:

static String s = "";
  public String toString() {

      if(this.value != 0) {
          if (this.hasLeft()) {
              this.getLeft().toString();
          }
          s += this.getValueString() + ", ";
          if (this.hasRight()) {
              this.getRight().toString();
          }
      }
      return s;
  }

以及树类中的方法,分别调用对树根的遍历:

public String toString() {
    return "tree[" + root.toString() + "]";
  }

现在,我想要的输出应该是这样的:

tree[x,y,z]

我的当前输出如下所示:

tree[x,y,z, ]

我尝试将值填充到数组中,但是我正在努力解决这个问题,因为数组不能是可变长度的,除非它是一个arraylist,我们还不允许使用它。此外,我们不允许使用任何迭代解。我只是不明白我怎么能打印出没有任何额外逗号/空格的整个东西。任何帮助都将不胜感激。

bq3bfh9z

bq3bfh9z1#

在使用静态字符串时,请检查字符串是否为空,并相应地按以下方式处理:

public String toString() {

  if(this.value != 0) {
      if (this.hasLeft()) {
          this.getLeft().toString();
      }

      if(s.equals("")){
          s += this.getValueString();
      }else{
          s += ", " + this.getValueString();
      }

      if (this.hasRight()) {
          this.getRight().toString();
      }
  }
  return s;
}

相关问题