如何打印一棵树(Java)
2017-05-25 15:07 猎手家园 阅读(4647) 评论(0) 编辑 收藏 举报1、有一棵多叉树,将它打印出来。
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); } } } }
2、按层打印一棵树
下面抛个砖,一棵树,如何按层去打印呢?
我使用了一个最笨的办法,就是先存在一个list里,然后再排序打印,我知道这不是我想要的结果,但我确实想不出其它方法了,希望看到的大神抽空回个帖子,万分感谢!
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; /** * 需求:按层打印一棵树 * 说明:树是保存在一个链表中 * created by wangjunfu on 2017-05-25. */ public class TreeNode_Level { Integer level; String data; TreeNode_Level parent; LinkedList<TreeNode_Level> childlist; public Integer getLevel() { return level; } public void setLevel(Integer level) { this.level = level; } TreeNode_Level() { data = null; childlist = new LinkedList(); parent = null; } // 递归读取一棵树 private ArrayList<TreeNode_Level> displayTree(TreeNode_Level f, int level) { ArrayList<TreeNode_Level> result = new ArrayList<>(); if (f == null) { return result; } for (int i = 0; i < f.childlist.size(); i++) { TreeNode_Level obj = f.childlist.get(i); obj.level = level; result.add(obj); if (!obj.childlist.isEmpty()) { displayTree(obj, level + 1); } } return result; } // 排序、按层打印结果 private void print() { TreeNode_Level f = null; // 到库里取数据 ArrayList<TreeNode_Level> list = displayTree(f, level = 1); Collections.sort(list, new Comparator<TreeNode_Level>() { @Override public int compare(TreeNode_Level o1, TreeNode_Level o2) { // 正序排序 return o1.getLevel().compareTo(o2.getLevel()); } }); list.forEach(item -> System.out.println(item.data)); } }
欢迎关注我的公众号:云栖语,不一样的研发视界。
云栖语微信公众号:change-1978