找到树中多个路径之间的公共最短边

时间:2013-03-09 06:53:12

标签: algorithm data-structures tree graph-theory

给定无向加权树(N节点,N-1双向边缘,不一定是二叉树)。 输入将是一些节点之间的简单路径(从起始节点到最低共同祖先到结束节点),例如1-> 4,2-> 10。找到所有给定路径的最短边缘(属于)。

1 个答案:

答案 0 :(得分:0)

基本上,在每个节点上计算穿过它的路径数。设置这些计数后,处理树并找到最短的公共边。公共边缘将是每个端点的计数等于路径数量的边缘。

i = 0

// set up counts
for each path p
  for each node n on path
    if n.count != i // early path stop condition, past common ancestor
      break // go to next path
    n.count++
  i++

current = root
shortestEdge = null

// find shortest edge
while true
  for each child c of current
    if c.count == pathCount
      shortestEdge = shortest(shortestEdge, edge(current, c))
      current = c
      break // out of for-loop
    else
      stop // stop while-loop