0

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());
        
    }
Ava
  • 3
  • 2
  • This is a good example of why methods shouldn't have [side effects](https://en.wikipedia.org/wiki/Side_effect_(computer_science)). If the traversal returned an arraylist result, then the caller could easily manipulate and print if desired, or do other programmatic things. The downside is somewhat more complex implementation and memory consumption. – ggorlen Sep 26 '22 at 13:51

3 Answers3

1

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

trincot
  • 317,000
  • 35
  • 244
  • 286
0

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());
talex
  • 17,973
  • 3
  • 29
  • 66
0

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).