I want to have a tree in memory, where each node can have multiple children. I would also need to reference this tree as a flat structure by index. for example:
a1
b1
b2
b3
c1
d1
e1
e2
d2
f1
Would be represented as a flat structure as I laid out (i.e.; a1=0, b1=1, d1=5, etc..)
Ideally I would want lookup by index to be O(1), and support insert, add, remove, etc.. with a bonus of it being threadsafe, but if that is not possible, let me know.
If you have a reasonably balanced tree, you can get indexed references in O(log n) time – just store in each node a count of the number of nodes under it, and update the counts along the path to a modified leaf when you do inserts, deletions, etc. Then you can compute an indexed access by looking at the node counts on each child when you descend from the root. How important is it to you that indexed references be O(1) instead of O(log n)?
If modifications are infrequent with respect to accesses, you could compute a side vector of pointers to nodes when you are finished with a set of modifications, by doing a tree traversal. Then you could get O(1) access to individual nodes by referencing the side vector, until the next time you modify the tree. The cost is that you have to do an O(n) tree traversal after doing modifications before you can get back to O(1) node lookups. Is your access pattern such that this would be a good tradeoff for you?