我们使用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