这是问题:
a 二维数组relation[n][2]表示节点之间的关系,例如relation[0]等于{2,4},所以节点2和节点4之间存在邻接关系,不包含循环关系.
我想将树结构保存在哈希图中,所以我尝试编写如下代码:
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);
}
}
似乎它不起作用,但我不知道如何解决它,有人可以帮助我吗?谢谢!