What's an elegant way of handling duplicates in a Binary Search Tree? Let's assume each key will have several different values associated. What I need to do is iterate over all values in order. So if I had 2 values A and B with key 1, and one value C with key 2, I would like to get pairs: (1,A), (1,B), (2,C), when calling something like TreeIterator.next();
I can think of:
visited
flag Any other suggestions? As a general guideline, i would like the Tree implementation to be as abstract as possible.
It sounds like basically you do want a list of values for each key, yes. So the process of adding to the map is:
When iterating over the map, your general pattern is:
Of course, if you don't need to implement this yourself for learning purposes, you could use a ready-made multimap, such as Guava 's TreeMultimap
. If you are implementing it for self-education, I'd start off by implementing a "normal" binary search map, and then going on from there.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.