這裏的問題:如何在散列表中保存樹結構?
一個二維數組關係[N] [2]表示節點之間的關係,對於爲例關係[0]等於{2,4},所以有一個adjancency關係在節點2和節點4之間,並且不包含循環關係。
我想救樹結構中一個HashMap,所以我試着寫我的代碼如下圖所示:
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它不工作,但我不知道如何解決它可以,有人幫助我?謝謝!
你能給輸入的例子,預期與實際輸出? –
從技術上講,你可以做'graph.put(0,tree);'它將被存儲在一個HashMap中。雖然我確定那不是你想要的,哈哈。 – byxor
你能解釋一下用例嗎?也許有比在散列圖中存儲樹更好的解決方案。例如,也許你需要一個樹狀結構來照原樣使用,但同時節點有一些ID需要保存在另一個結構中(例如:HashMap),以便快速檢索節點。 – andreim