【问题标题】:Printing inorder traversal in Java with commas用逗号在Java中打印中序遍历
【发布时间】:2021-03-26 02:48:05
【问题描述】:

我正在尝试在 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

}

(两个类都已经实现了插入方法)

现在我正在尝试为 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;
  }

和Tree类中的一个方法分别调用对树根的遍历:

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

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

tree[x,y,z]

我当前的输出如下所示:

tree[x,y,z, ]

我已尝试将值填充到数组中,但我正在为此苦苦挣扎,因为数组不能是可变长度的,除非它是一个 ArrayList,我们还不允许使用它。此外,我们不允许使用任何迭代解决方案。我只是不明白如何以没有任何额外逗号/空格的方式打印整个内容。任何帮助将不胜感激。

【问题讨论】:

标签: java recursion binary-search-tree


【解决方案1】:

当您使用的是静态字符串时,请检查字符串是否为空,并按如下方式进行处理:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多