KJW
KJW

Reputation: 15251

Java: preorderEnumeration in TreeModel, how to get depthindex and sibling index?

    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?

Upvotes: 0

Views: 552

Answers (1)

Yves Martin
Yves Martin

Reputation: 10361

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 }

Upvotes: 1

Related Questions