我們使用Java中指定的DefaultMutableTreeNode
實現了一個樹結構。使用DefaultMutableTreeNode創建的遍歷樹
是否有任何方法遍歷它,這是內置的?
如果不是,請提出其他技巧。
我們使用Java中指定的DefaultMutableTreeNode
實現了一個樹結構。使用DefaultMutableTreeNode創建的遍歷樹
是否有任何方法遍歷它,這是內置的?
如果不是,請提出其他技巧。
如果你的意思是你想遍歷樹,你可以調用breadthFirstEnumeration()
或depthFirstEnumeration()
來遍歷樹中的所有節點。
實施例:
DefaultMutableTreeNode root = ...
Enumeration en = root.depthFirstEnumeration();
while (en.hasMoreElements()) {
// Unfortunately the enumeration isn't genericised so we need to downcast
// when calling nextElement():
DefaultMutableTreeNode node = (DefaultMutableTreeNode) en.nextElement();
}
正確,breadtFirst是序。預購(第一根,然後孩子們)支持,以及(preorderEnumeration)
你必須在理論上四種方法從一個節點在樹(DefaultMutableTreeNode
):
breadthFirstEnumeration
depthFirstEnumeration
preorderEnumeration
postorderEnumeration
,但實際上深度優先實現爲後序。
JavaDoc在這些方法上的差異有點簡單。我來到這裏尋找一個答案,但我做了我自己的測試結束,代碼看起來像:
TreeModel model = tree.getModel();
DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) model.getRoot();
// Just changing enumeration kind here
Enumeration<DefaultMutableTreeNode> en = rootNode.preorderEnumeration();
while (en.hasMoreElements())
{
DefaultMutableTreeNode node = en.nextElement();
TreeNode[] path = node.getPath();
System.out.println((node.isLeaf() ? " - " : "+ ") + path[path.length - 1]);
}
我可以改進與縮進成正比的水平,但它只是一個快速的黑客攻擊。
那麼,有什麼區別?
preorderEnumeration
=從樹的頂部底部,因爲如果你使用向下箭頭走就postorderEnumeration
= depthFirstEnumeration
=首先列出的第一條路徑的最深的葉子,那麼他們的父母,然後最深第二條路徑的葉子等breadthFirstEnumeration
=列出在第一級上的元素,然後在第二級中的元素,依此類推更具體:
+ Root
+ Folder 1
- Leaf F1
- Leaf F1
+ Folder 2
+ Sub-folder 1
- Leaf SF1
- Leaf SF1
+ Sub-folder 2
- Leaf SF2
- Leaf SF2
♦預訂:如上所示
♦深度優先/後序:
葉F1,葉F1,文件夾1
葉SF1,SF1葉,子文件夾1
葉SF 2,葉SF2,子文件夾2 ,文件夾2,根
♦BreathFirst:
根
文件夾1,文件夾2
葉F1,葉F1,子文件夾1,子文件夾2
葉SF 1,葉SF 1,葉片SF 2 ,Leaf SF 2
下面是3種枚舉方法的另一種描述,它可能更容易理解。
en = root.breadthFirstEnumeration();
//Enumeration lists all nodes at depth 0 (aka root)
//Then all nodes at depth 1 (aka root's children, top to bottom ordering)
//Then all nodes at depth 2, and so on till max depth reached
en = root.preorderEnumeration();
//Imagine your JTree is fully expanded (where each node = a row)
//Enumeration will list nodes from top to bottom (regardless of leaf or not)
en = root.postorderEnumeration(); //Equivalent to root.depthFirstEnumeration();
//Imagine a fully expanded copy of your JTree (where each node = a row)
//This will allow you to visualize what Enumeration List will look like
while(treecopy.hasNodes()) {
list 1st leaf sighted going from top to bottom, then remove that leaf }
//as the leafs are removed, branches then become leafs, and root is last enumerated.
本來我沒有說我的意思,我的意思是它作爲一種可視化協助,但我不小心說了。我現在改變了它,希望更清楚,謝謝你的反饋。 – neokyle 2013-07-15 03:37:21
解析它是什麼意思?通常你會解析一個表達式來構建一個內部表示(就像你已經擁有的樹結構一樣)。你只是想要遍歷樹? – Adamski 2009-09-24 10:38:44
對不起,我的意思是遍歷它。 – fixxxer 2009-09-24 10:42:31