我们有一个用Java语言指定的DefaultMutableTreeNode实现的树形结构。
有没有什么方法可以遍历它,那就是内置?
如果没有,请建议其他技术。
发布于 2009-09-24 10:39:41
如果您想遍历树,那么可以调用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();
}发布于 2010-12-17 00:14:24
从理论上讲,有四种方法可以从节点(DefaultMutableTreeNode)遍历树:
breadthFirstEnumerationdepthFirstEnumerationpreorderEnumerationpostorderEnumeration但实际上深度优先是以后序的形式实现的。
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 =从树的顶部到底部,就像使用向下箭头遍历一样itpostorderEnumeration = depthFirstEnumeration =首先列出第一个路径的最深的叶子,然后是它们的父级,然后是第二个路径的最深的叶子,etc.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、叶SF 2
发布于 2013-07-12 08:49:03
下面是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.https://stackoverflow.com/questions/1470857
复制相似问题