Дерево перемещения по умолчанию из DefaultMutableTreeNode
У нас есть древовидная структура, реализованная с использованием DefaultMutableTreeNode
, указанного в Java.
Есть ли способ его перемещения, который встроен?
Если нет, предложите другие методы.
Ответы
Ответ 1
Если вы хотите, чтобы вы проходили дерево, вы можете вызвать 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();
}
Ответ 2
В теории есть четыре способа передвижения дерева из node (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
♦ Предзаказ: как показано выше
♦ DepthFirst/Postorder:
Лист 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
Ответ 3
Вот еще одно описание 3 перечисляющих методов, которые могут быть проще понять.
en = root.breadthFirstEnumeration();
//Enumeration lists all nodes at depth 0 (aka root)
//Then all nodes at depth 1 (aka root 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.
Ответ 4
Правильно, breadtFirst - inorder. Предзаказ (первый корень, потом дети) также поддерживается (preorderEnumeration)