Home > Software design >  How do I delete the last whitespace after recursively printing Binary tree root
How do I delete the last whitespace after recursively printing Binary tree root

Time:09-27

the code itself is working though whenever I try to print the results which are integers of the following form: 1 2 3 4 5 I end up with an extra whitespace after the 5, how can I delete the last whitespace while keeping the integers separated on one line

public void inorder() {
        inrec(root);
    }
    private void inrec(BTNode<E> root) {
        
        if (root == null) {
            return;
        }
            inrec(root.getLeft());
            System.out.printf(root.getData() " ");
            
            
            inrec(root.getRight());
        
    }

CodePudding user response:

Instead of building the string, collect the values in an ArrayList. Then leave it to the caller to do something with that.

So:

   private void inrec(BTNode<E> root, ArrayList<E> arr) {
        if (root == null) {
            return;
        }
        inrec(root.getLeft(), arr);
        arr.add(root.getData());
        inrec(root.getRight(), arr);
    }

    public void inorder(ArrayList<E> arr) {
        inrec(root, arr);
    }

The caller could then do this:

    var arr = new ArrayList<E>();
    inorder(arr);
    System.out.println(
        arr.stream()
           .map(Object::toString)
           .collect(Collectors.joining(" "))
    );

Or, use any of the other ways to convert an array list to string

CodePudding user response:

Try this.

public void inorder() {
    inrec(root, "", "");
}

private void inrec(Node<E> root, String prefix, String suffix) {
    if (root == null)
        return;
    System.out.print(prefix);
    inrec(root.getLeft(), "", " ");
    System.out.print(root.getData());
    inrec(root.getRight(), " ", "");
    System.out.print(suffix);
}

If you change inorder() to

public void inorder() {
    inrec(root, "(", ")");
}

It will print (1 2 3 4 5).

CodePudding user response:

You generally can't delete symbols printed to System.out.

You have two options.

  • Collect all you want to print in StringBuilder delete witespace and then print.
  • Print witespace before integer. Skip printing if it is first item. To do that you may create boolean flag to track if it is first print.

Example:

Create field

boolean isFirst = true;

Then use

if(!isFirst){
   System.out.print(" ");
} else {
   isFirst = false;
}
System.out.printf(root.getData());
  • Related