0
    for (Enumeration e = root.preorderEnumeration(); e.hasMoreElements() && theNode == null;) {
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();

    }

For that example above, how can you find out how deep you are in the tree branch? If you are iterating over siblings, how do you get it's index?

mKorbel
  • 109,525
  • 20
  • 134
  • 319
KJW
  • 15,035
  • 47
  • 137
  • 243

1 Answers1

1

You can get the depth by counting the number of parents iterating on getParent() from node until result is null.

You can get node's index thanks to node.getIndex(node.getParent()).

If you need both information for each node you traverse, I recommend you for efficiency to write your own traversor code, either inspired from DefaultMutableTreeNode.getNextNode() or DefaultMutableTreeNode.PreorderEnumeration inner class. In that later case, the generated stack should contain a structure { node, treeDepth, siblingIndex }

Yves Martin
  • 10,217
  • 2
  • 38
  • 77
  • don't re-invent the wheel, there's api for getting the node's distance from the root: node.getLevel() Wasn't aware of it until recently, skimming the api doc works wonders :-) – kleopatra Mar 07 '12 at 10:42
  • I agree. getLevel() does exactly the count I describe but it is not efficient if you need that information for each node. – Yves Martin Mar 07 '12 at 15:34