We have a tree structure implemented using the DefaultMutableTreeNode specified in Java.
Is there any way of traversing it, that is inbuilt?
If not, please suggest other techniques.
We have a tree structure implemented using the DefaultMutableTreeNode specified in Java.
Is there any way of traversing it, that is inbuilt?
If not, please suggest other techniques.
You have in theory four ways to walk the tree from a node (DefaultMutableTreeNode):
breadthFirstEnumerationdepthFirstEnumerationpreorderEnumerationpostorderEnumerationbut actually depth first is implemented as postorder.
The JavaDoc is a bit terse on the differences on these methods. I came here looking for an answer, but I ended by doing the test myself, with a code looking like:
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]);
}
I could have refined with indentation proportional to level, but it was just a quick hack.
So, what are the differences?
preorderEnumeration = from top of tree to bottom, as if you were using the down arrow to walk itpostorderEnumeration = depthFirstEnumeration = first list the deepest leafs of the first path, then their parent, then the deepest leafs of the second path, etc.breadthFirstEnumeration = list the elements at the first level, then the elements at the second level, and so onTo be more concrete:
+ Root
+ Folder 1
- Leaf F1
- Leaf F1
+ Folder 2
+ Sub-folder 1
- Leaf SF1
- Leaf SF1
+ Sub-folder 2
- Leaf SF2
- Leaf SF2
♦ Preorder: as shown above
♦ DepthFirst/Postorder:
Leaf F1, Leaf F1, Folder 1
Leaf SF1, Leaf SF1, Sub-folder 1
Leaf SF 2, Leaf SF2, Sub-folder 2, Folder 2, Root
♦ BreathFirst:
Root
Folder 1, Folder 2
Leaf F1, Leaf F1, Sub-folder 1, Sub-folder 2
Leaf SF 1, Leaf SF 1, Leaf SF 2, Leaf SF 2