Java找root节点_java – 树的分区压缩以及如何将节点压缩到root

我试图通过让它们指向传递给的参数节点的根来压缩给定节点的所有祖先

private E compressToRoot (E e) throws IllegalArgumentException;

例如,在上图中,如果我执行compressToRoot(D),则D将直接指向A,而C将直接指向A.如果参数和根之间存在其他节点,则它们都将指向A.

所有标签和箭头都存储在两个单独的地图中:

private Map parentMap = new HashMap(); //labels + arrows

我可以通过(1)保持D和根之间的所有节点来完成这个方法. (2)将设置的所有元素指向(make parent)根(3)返回根.

但是,我仍然坚持如何遍历此地图以获取根.所以,对于方法,我会做一些事情

private E compressToRoot (E e) throws IllegalArgumentException {

Set collectLables = new HashSet();

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);

}

}

}

但我不知道如何循环通过给定节点的父节点到根节点.

解决方法:

递归是相当的,但如果到根的最长路径的长度可能变大,则支持迭代方法.你不想用完堆栈.

private E compressToRoot(E node) {

if (parentMap.get(node) != node)

parentMap.set(node, compressToRoot(node));

return parentMap.get(node);

}

private E compressToRoot(E cursor) {

E node;

ArrayList nodes = new ArrayList();

while ((node = parentMap.get(cursor)) != cursor) {

nodes.add(cursor);

cursor = node;

}

for (node : nodes)

parentMap.set(node, cursor);

return cursor;

}

标签:java,algorithm,graph,data-structures,map

来源: https://codeday.me/bug/20190629/1330253.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值