Here's the question:
a Two-dimensional array relation[n][2] represent the relation between the nodes, for exemple relation[0] equals {2,4}, so there is an adjancency relation between node 2 and node 4, and contains no cyclic relation.
I wanna save the tree structure in a hashmap, so I tried to write my code like below:
Map<Integer, LinkedList<Integer>> graph = new HashMap<Integer, LinkedList<Integer>>();
for (int i = 0; i < n; i++) {
int A = relation[i][0];
int B = relation[i][1];
if (graph.get(A) == null) {
List<Integer> tempList = new LinkedList();
tempList.add(B);
graph.put(A, tempList);
} else {
graph.get(A).add(B);
}
if (graph.get(B) == null) {
List<Integer> tempList = new LinkedList();
tempList.add(A);
graph.put(B, tempList);
} else {
graph.get(B).add(A);
}
}
appearently it doesn't work, but I dont know how to fix it, can somebody help me pls? thanks!