Reputation: 381
I am working on a visualization tool where i am trying to represent a set of nodes in a tree-like structure. In the backend:
Example:
A -> B -> (C -> null / D -> E/F/G)
(A has B as a child, B has C and D as children. C has no children, D has E/F/G as children)
I am using the React D3 Tree library for the visualization. Example data the tree accepts:
const myTreeData = [
{
name: 'Top Level',
children: [
{
name: 'Level 2: A',
children: [
name: 'Level 3: C',
children:[
name: 'Level 4: D', children: []
]
]
},
{
name: 'Level 2: B',
},
],
},
];
Ie. the nodes themselves contain an array with references to their own children.If they don't have any children, the array is empty.
I am having trouble figuring out what algorithm i need to use to convert my linked list to this tree-structure. Primarily, how to deal with the fact that each level can have an arbitrary amount of nodes. I've tried to do it iteratively by representing each "step" in the linked list as a level, then going backwards and linking each level to the one above it. However, the code gets very complicated and it's hard to generalize.
I suspect there is a very simple recursive solution to this problem, but i think the data structure used by the tree throws me off (having a hard time understanding how to pass that top-level children object around)
Upvotes: 1
Views: 179
Reputation: 381
I managed to solve it. Its probably inefficient, but for whoevers curious:
Upvotes: 1