简体   繁体   中英

Duplicates in a Binary Search Tree

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:

  • Each node has a key, and an array of values where values with the same key go
  • Each node has a 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:

  • Does key exist?
    • If so, add value to the existing list.
    • If not, create a new node in the tree at the appropriate point (as normal) and start with a list of one value

When iterating over the map, your general pattern is:

  • Yield all values from the left node (smaller keys)
  • Yield all values for this node - (key, value1), (key, value2) etc
  • Yield all values from the right node (larger keys)

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.

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