Java TreeMap 排序选项?
我听说 java 类 TreeMap 使用 RB 树的实现。 如果是这种情况,如何在 TreeMap 上进行中序、前序和后序树遍历?
或者这是不可能的?
I've been told that the java class TreeMap uses an implementation of a RB tree. If this is the case, how does one do an inorder, preorder and postorder tree-walk on a TreeMap?
Or is this not possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将无法使用 Collections 库中实现的 TreeMap 来执行此操作。 这是 Java 中的红黑树,你可以看看。 查看
printTree()
方法,了解它们如何按排序顺序遍历树。由此,也许您可以编写自己的方法来以所有三个顺序遍历树。
You wouldn't be able to do this with the TreeMap implemented in the Collections library. Here's an implementation of a Red-Black Tree in Java that you can look at though. Check out the
printTree()
methods to see how they walk the tree in sorted order.From that maybe you can write your own methods to traverse the tree in all three orders.
AFAIK TreeSet/TreeMap 类实际上并不公开其任何内部结构,而只是符合 Set/Map 接口。 迭代器仅保证按升序进行。
我有点困惑为什么你想要按顺序扫描这些节点,因为这些树的目标不是表示对象之间的关系(例如数学公式),而只是存储所有它们并有效地检索它们。
AFAIK the TreeSet/TreeMap classes don't actually expose any of their internals and merely conform to the Set/Map interface. The iterator is only guaranteed to go in an ascending order.
I am a little perplexed as to why you would want to scan these nodes in an inorder since the goal of these trees is not to represent relations between objects (e.g., math formulae) but rather just to store all of them and retrieve them efficiently.
您至少可以使用迭代器和 foreach 循环进行中序遍历:
但是,其他海报是正确的:Java 不公开任何树机制,因此在此视图中不可能进行预序或后序。
You can at least do the inorder walk using the iterator and a for each loop:
However, the other posters are right: Java doesn't expose any of the tree mechanics, so a preorder or postorder isn't possible at this view.