for (Enumeration e = root.preorderEnumeration(); e.hasMoreElements() && theNode == null;) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();
}
对于上面的例子,你如何知道你在 Twig 中有多深?如果您要迭代 sibling ,如何获取它的索引?
最佳答案
您可以通过计算在 getParent()
上迭代的父项数量来获取深度。来自node
直到结果为 null
.
您可以获得node
的索引感谢 node.getIndex(node.getParent())
.
如果您需要遍历的每个节点的这两种信息,为了提高效率,我建议您编写自己的遍历器代码,其灵感来自 DefaultMutableTreeNode.getNextNode()
或DefaultMutableTreeNode.PreorderEnumeration
内部类。在后一种情况下,生成的堆栈应包含结构 { node, treeDepth, siblingIndex }
关于Java:TreeModel中的preorderEnumeration,如何获取深度索引和兄弟索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9558797/