Traversing tree made from DefaultMutableTreeNode

Viewed 14721

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.

4 Answers

You have in theory four ways to walk the tree from a node (DefaultMutableTreeNode):

  • breadthFirstEnumeration
  • depthFirstEnumeration
  • preorderEnumeration
  • postorderEnumeration

but 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 it
  • postorderEnumeration = 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 on

To 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

Related