我試圖壓縮給定節點的所有祖先通過使它們指向參數節點傳遞到
private E compressToRoot (E e) throws IllegalArgumentException;
根
例如,在上面的圖片中,如果我執行了compressToRoot(D),那麼D將直接指向A,C將直接指向A.如果參數和根之間存在其他節點,則它們都指向A.
所有的實驗室els和箭頭存儲在兩個單獨的地圖中:我可以通過以下方法來完成此方法:(1)將D和根中的所有節點保存在一組中。 (2)使設定點的所有元素(作爲父母)爲根(3)返回根。
但是,我被困在如何遍歷這個地圖到根。因此,對於該方法,我會做沿着
private E compressToRoot (E e) throws IllegalArgumentException {
Set<E> collectLables = new HashSet<E>();
E root = null;
//get root.
for (E cycle : parentMap.keys()) {
while (parentMap.get(e) != e)
e = parentMap.get(e);
if (parentMap.get(e) == e)
root = cycle;
}
//collect all labels from parameter to root.
for (E element : parentMap.keys()) {
while (parentMap.get(e) != root) {
collectLables.add(element);
}
}
}
線的東西,但我不知道我怎麼可以通過給定節點一路到根的父母週期。
爲什麼E指向圖像中的A? – Origin