首页 > 代码库 > 如何打印一棵树(Java)

如何打印一棵树(Java)

有一棵多叉树,将它打印出来。

import java.util.LinkedList;/** * 需求:按层打印一棵树 * 说明:树是保存在一个链表中 * created by wangjunfu on 2017-05-25. */public class TreeNode {    String data;    TreeNode parent;    LinkedList<TreeNode> childlist;    TreeNode() {        data = null;        childlist = new LinkedList();        parent = null;    }    //递归显示并打印一棵树    private static void displayTree(TreeNode f, int level) {        String preStr = "";     // 打印前缀        for (int i = 0; i < level; i++) {            preStr += "    ";        }        for (int i = 0; i < f.childlist.size(); i++) {            TreeNode t = f.childlist.get(i);            System.out.println(preStr + "-" + t.data);            if (!t.childlist.isEmpty()) {                displayTree(t, level + 1);            }        }    }}

 

如何打印一棵树(Java)