I’ve a requirement to define Data Structure and Algorithm for Circular Data Graph for web client.
At server, data will provided in a 2 column CSV format (e.g. Sender, Receiver).
Final output will be rendered in JSON format and sent to web request.
I have seen some Tree examples which can help in Parent Child relationships. But In my case, I have a recursive relationship i.e. A Parent's grand child can also be used as a Parent; which make life bit difficult as I run in to infinite loop.
Data:
Sender,Receiver
A,B
A,H
B,C
B,D
D,E
E,F
F,G
G,C
H,I
H,J
J,K
K,L
L,M
M,K
L,N
N,O
N,P
P,A
N,Q
Client may render like this (I only care about Java Structure):
Client can request any Node and I have to generate the whole Tree and send the response i.e. A, K or N.

Questions:
- What will be the best
Data Structurefor this requirement? For
exampleTreelike or any other? - Should I write my own logic to read
the data and set inTreeor are there any standard algorithms out
there? - What’s the best way of avoiding the recursion?
Any working example will really help here 🙂
Please also see my working solution below.
I’m sure the tree examples you’ve found already are correct on how to implement a tree like structure. In your case you have the added complication that it is possible for recursive loops to exist as certain children will be exact object references to one of their ancestors. (right?)
Because of this complication any process that attempts to traverse your tree by iterating over the children of each node will loop around these recursive connections until stack overflow occurs.
In this case you are no longer really dealing with a tree. Mathematically, a tree is defined as a Graph without cycles. In your case you have cycles, and therefore not a tree but a circular graph.
I have dealt with such situations in the past, and I think you can you can deal with this in two ways.
Break the cycles (at an object level), to return to a tree. Where one of these recursive connections happens, do not place the real object reference to the ancestor, but a stub that indicates which object it connects to without being the object reference to that item.
Accept you have a circular graph, and ensure your code can cope with this when traversing the graph. Ensure that any client code interacting with your graph can detect when it is in a recursive branch and deal with it appropriately.
IMHO Option 2 is not very attractive as you may find it hard to guarantee the constraint and it often leads to bugs. As long as you can allocate each item in the tree a unique identifier, option 1 works well, although clients will still need an awareness of this possibility occurring so they can process the de-coupled link and represent it correctly (for instance in a tree view UI). You are still wanting to model a circular graph, but are going to use a tree to represent it at an object level as it simplifies the code (and presentation).
Full Example of Option 1: