简体   繁体   English

如何使用dfs预购正确打印N元树

[英]How to print correctly an N-ary tree with dfs pre-order

I did a recursive pre-order depth-first search function of an N-ary tree in order to traverse it and print,but I want to remove the last space in the print. 为了遍历和打印,我对N元树进行了递归的深度优先搜索,但是我想删除打印中的最后一个空格。 How can I do that without define other functions? 不定义其他功能怎么办?

 public void printdfs() {

    int sz = this.children.size();
    if (sz > 0) {
        System.out.print(getValue() + " ");
    }
    else {
        System.out.print(" " + getValue());
    }


    for (int i = 0; i < sz; i++) {
        MyTree object = this.children.get(i);
        System.out.print(".");
        object.printdfs();
    }

}

Output: 8 .20 .25 . 95. 70. 80. 30. 40. 10. 9

My structure of the N-ary tree is: 我的N元树的结构是:

public class MyTree {
private int data;
private LinkedList<MyTree> children;

public MyTree(int data) {
    this.data = data;
    this.children = new LinkedList<>();
}
public int getValue() {
    return this.data;
}
public void addChild(MyTree child) {
    this.children.addFirst(child);
}
}

Something like this? 像这样吗

    for (int i = 0; i < childrens.size(); i++) {
       MyTree object = childrens.get(i);
       if (i == (childrens.size() - 1)) {
          object.printdfs().trim();
       }
       else {
          object.printdfs();
       }
    }

EDIT after comments: Would something like this work? 评论后编辑:像这样工作吗?

public void printdfs(PrintStream ps) {
    ps.print(getValue() + " ");
    for (int i = 0; i < childrens.size(); i++) {
       MyTree object = childrens.get(i);
       object.printdfs(ps);
    }
}

Then you have a reference to the Stream object you originally pass in to the printdfs() method and you can then print out a substring of the Stream's data after printdfs() returns. 然后,您可以引用最初传递给printdfs()方法的Stream对象,然后可以在printdfs()返回之后打印出Stream数据的子字符串。

Or maybe you just want something like this? 或者,也许您只想要这样的东西?

public void printdfs() {
    int sz = childrens.size();
    if (sz < 0) {
        System.out.print(getValue() + " ");
    }
    else {
        System.out.print(getValue());
    }
    for (int i = 0; i < sz; i++) {
       MyTree object = childrens.get(i);
       object.printdfs();
    }
}

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

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