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