我试图通过让它们指向传递给的参数节点的根来压缩给定节点的所有祖先
private E compressToRoot (E e) throws IllegalArgumentException;
例如,在上图中,如果我执行 compressToRoot(D),则 D 将直接指向 A,C 将直接指向 A。如果参数和根之间还有其他节点,那么它们都将指向 A。
所有标签和箭头都存储在两个单独的地图中:
private Map<E,E> parentMap = new HashMap<E,E>(); //labels + arrows
我可以通过 (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);
}
}
}
但是我不确定如何循环通过给定节点的父节点一直到根节点。