简体   繁体   中英

Printing inorder traversal in Java with commas

I am trying to print an inorder traversal implementation of a Binary tree in Java. I am given the following two classes:

public class Tree {

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

}
  

as well as

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

}

(with an insert method already implemented, for both classes)

and now I am trying to implement a toString method for the TreeNode class, to implement the inorder traversal and return it as a string:

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

and a method in the Tree class respectively to call the traversal on a Tree root:

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

Now, while the output I want shall look like this:

tree[x,y,z]

my current output looks like this:

tree[x,y,z, ]

I have tried to fill the values into an array instead, but I'm struggling with that since an array can't be of variable length unless it's an ArrayList, which we are not yet allowed to use. Moreover, we are not allowed to use any iterative solutions. I just don't understand how I can print the whole thing in a manner that there aren't any additional commas/spaces. Any help would be hugely appreciated.

As you are using a Static string, check if string is empty and accordingly process it as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM