I've been trying to efficiently create trees by assigning a child to its parent and then deleting it via it.remove()
:
for (OgOrganizationTreeDTO parent : parents) {
setChildren(parent, organizationTree);
}
Here is the implementation of the setChildren
function
private void setChildren(OgOrganizationTreeDTO root, List<OgOrganizationTreeDTO> allOrganizations) {
if (allOrganizations.isEmpty()) {
return ;
}
Iterator<OgOrganizationTreeDTO> it = allOrganizations.iterator();
while (it.hasNext()) {
OgOrganizationTreeDTO potentialChild = it.next();
if (potentialChild.getIdParentId() != null && potentialChild.getIdParentId().equals(root.getId())) {
root.addChild(potentialChild);
it.remove();
setChildren(potentialChild, allOrganizations);
}
}
}
I am using a LinkedList and I get a ConcurrentModificationException
. I've solved the problem by passing a copy of allOrganizations
to the recursive setChildren
function like so new LinkedList<>(allOrganizations)
, but the copy part takes O(n)
time and I don't want that.
I've also tried using LinkedBlockingQueue
, but I've found out that deletion takes O(n)
time.
I want to take advantage of LinkedList
O(1)
remove, so everytime I add a child, and recur on it the list becomes smaller.
I've also successfully implemented a solution with HashSet
by marking individual nodes as seen, and setting the base case to hashSet.size() == allOrganizations.size()
, but I still keep recurring over the same size List, so this doesn't help me other.
Is there any way of accomplishing my goal of using LinkedList
O(1)
remove, or is there an even more efficient alternate approach to this ?