java - 如何求多叉树两个任意节点的最短路径呢?
ringa_lee
ringa_lee 2017-04-18 10:48:59
0
2
601

每个节点的数据结构是一个value ,和这个节点的所有子节点

ringa_lee
ringa_lee

ringa_lee

reply all(2)
Ty80

There are n nodes.

  1. Convert the tree to an undirected graph, and then use n-time single-source shortest path algorithms such as dijkstra and spfa or 1-time floyd multi-source shortest path algorithm to find the values ​​of any two nodes. But when n is relatively large, the memory overhead of storing the value is large.

  2. Make the tree a rooted tree, and each node i stores the distance di to the root. When querying two nodes di,dj, find the common ancestor dk of the two nodes, then d(i,j)=di+dj-dk*2. For information on common ancestors, please refer to the Tarjan algorithm.

小葫芦

Consider Floyd’s algorithm as an undirected graph.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!