简体   繁体   English

Java TreeMap排序选项?

[英]Java TreeMap sorting options?

I've been told that the java class TreeMap uses an implementation of a RB tree. 我被告知java类TreeMap使用RB树的实现。 If this is the case, how does one do an inorder, preorder and postorder tree-walk on a TreeMap? 如果是这种情况,如何在TreeMap上进行顺序,预订和后序树步行?

Or is this not possible? 或者这不可能吗?

You wouldn't be able to do this with the TreeMap implemented in the Collections library. 您无法使用Collections库中实现的TreeMap执行此操作。 Here's an implementation of a Red-Black Tree in Java that you can look at though. 这里是Java中的红黑树的实现,你可以看一下。 Check out the printTree() methods to see how they walk the tree in sorted order. 查看printTree()方法,了解它们如何按排序顺序遍历树。

/**
 * Print all items.
 */
public void printTree( ) {
    printTree( header.right );
}

/**
 * Internal method to print a subtree in sorted order.
 * @param t the node that roots the tree.
 */
private void printTree( RedBlackNode t ) {
    if( t != nullNode ) {
        printTree( t.left );
        System.out.println( t.element );
        printTree( t.right );
    }
}

From that maybe you can write your own methods to traverse the tree in all three orders. 从那可能你可以编写自己的方法来遍历所有三个命令中的树。

AFAIK the TreeSet/TreeMap classes don't actually expose any of their internals and merely conform to the Set/Map interface. AFAIK TreeSet / TreeMap类实际上不暴露它们的任何内部结构,只是符合Set / Map接口。 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 (eg, math formulae) but rather just to store all of them and retrieve them efficiently. 我有点困惑于为什么你想要按顺序扫描这些节点,因为这些树的目标不是表示对象之间的关系(例如,数学公式),而是仅存储所有这些节点并有效地检索它们。

You can at least do the inorder walk using the iterator and a for each loop: 您至少可以使用迭代器和每个循环执行inorder walk:

void inOrderWalk(TreeMap<K,V> treeMap) {
   //this will loop through the values in the map in sorted order (inorder traversal)
   for (Map.Entry<K,V> entry : treeMap.entrySet() {
        V value = entry.getValue();
        K key = entry.getKey()
   }
}

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. 但是,其他海报是正确的:Java不会暴露任何树机制,因此在此视图中无法进行预订或后序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM