如何使用dfs预订正确打印N-ary树

时间:2017-03-30 15:23:16

标签: java tree

我做了一个N-ary树的递归预先深度优先搜索功能,以便遍历它并打印,但我想删除打印中的最后一个空格。如果不定义其他功能,我怎么能这样做?

 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

我的N-ary树的结构是:

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

1 个答案:

答案 0 :(得分:0)

这样的东西?

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

评论后编辑:这样的工作会起作用吗?

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

然后您可以引用最初传入printdfs()方法的Stream对象,然后在printdfs()返回后打印出Stream数据的子字符串。

或许你只是想要这样的东西?

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