I'm trying to construct binary tree from given edges and root. I iterate over all lines and set left child to given node(and right child if second occurrence of given node is found). And when child node is set I remove this element from ArrayList and call function recursively on child.
List<Integer[]> edges = new ArrayList<>();
This array list is e.g:
3 4
3 0
4 5
1 3
2 4
and root is 1.
I have class Node
public class Node {
public Node left;
public Node right;
public int key;
public Node(int k) {
key = k;
left = null;
right = null;
}
...}
And my function to construct a tree is:
public static void edgeToNodes(Node root) {
if (root == null) return;
int count = 0;
for (Iterator<Integer[]> iterator = edges.iterator(); iterator.hasNext(); ) {
Integer[] edge = iterator.next();
for (int i = 0; i < edge.length; i++) {
if (edge[i] == root.key) {
if (count == 0) {
Node left;
if (i == 0) {
left = new Node(edge[1]);
root.setLeft(left);
} else {
left = new Node(edge[0]);
root.setLeft(left);
}
iterator.remove();
count++;
edgeToNodes(left);
} else {
Node right;
if (i == 0) {
right = new Node(edge[1]);
root.setRight(right);
} else {
right = new Node(edge[0]);
root.setRight(right);
}
iterator.remove();
edgeToNodes(right);
}
}
}
}
}
Problem is that it gives me java.util.ConcurrentModificationException on line Integer[] edge = iterator.next(); and edgeToNodes(left); How can I avoid this exception?