views:

1778

answers:

3

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?

+1  A: 

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.

Uri
It's more a question of theory than application.
kylex
+4  A: 

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() method 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.

Bill the Lizard
A: 

You can at least do the inorder walk using the iterator and a for each loop:

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.

Rich