简体   繁体   English

递归打印二叉树根后如何删除最后一个空格

[英]How do I delete the last whitespace after recursively printing Binary tree root

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代码本身正在工作,但每当我尝试打印以下形式的整数的结果时:1 2 3 4 5 我最终在 5 之后有一个额外的空格,我怎样才能删除最后一个空格,同时保持整数分开一条线

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

Instead of building the string, collect the values in an ArrayList.不要构建字符串,而是收集 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或者,使用任何其他方法将数组列表转换为字符串

You generally can't delete symbols printed to System.out .您通常不能删除打印到System.out的符号。

You have two options.你有两个选择。

  • Collect all you want to print in StringBuilder delete witespace and then print.StringBuilder中收集所有要打印的内容,删除空白空间,然后打印。
  • Print witespace before integer.在 integer 之前打印空白空间。 Skip printing if it is first item.如果是第一项,则跳过打印。 To do that you may create boolean flag to track if it is first print.为此,您可以创建 boolean 标志来跟踪它是否是第一次打印。

Example:例子:

Create field创建字段

boolean isFirst = true;

Then use然后使用

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

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如果您将inorder()更改为

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

It will print (1 2 3 4 5) .它将打印(1 2 3 4 5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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