寻找祖先的算法

时间:2013-11-09 22:59:20

标签: algorithm graph tree

这是在考试中被问到的。能帮我找一个解决方案吗?

使用以下方法设计算法以查找给定节点(树或图形)的祖先数量:

  1. O(m)记忆
  2. 无限内存大小

2 个答案:

答案 0 :(得分:0)

算法将取决于树的设计。最简单的示例是包含其父节点的节点,在这种情况下,它将缩减为

int ancestors = 0;
while( node = node->parent) ancestors++;

约束在任何合理的实施中都不构成问题。

如果节点包含父节点,则它取决于树的结构。

  • 无序树的最复杂情况下,它需要完整的树搜索,计算祖先。
  • 对于搜索树,您只需要进行搜索。

答案 1 :(得分:0)

假设图中没有循环(在这种情况下,祖先没有意义)DFS循环可以用来计算任何节点k的祖先,只需在每次迭代中标记计数的节点,并且不要计算两次访问节点。

for i in graph visited[i] = false // for DFS

for i in graph counted[i] = false // for ancestors

int globalcount = 0; // count the no of ancestors

for i in graph DFS(i,k) //DFS-loop

def bool DFS(u,k) {   //K is the node whos ancestors want to find


if(!visited[u]) {

visited[u] = true // prevent re-entering

totalret = false // whether there is path from u to k

for each edge(u,v) {

retval = DFS(v)

if(retval&&!counted[u]&&u!=k) {  //there is path from u to k & u is not counted 

  globalcount++

  counted[u] = true

  totalret = true

}

}

if(u == k) return true

else return totalret

}

return counted[u] // if visited already and whether ancestor(k)?
}

print globalcount // total ancestor(k)

空间复杂度:O(V) V:没有顶点

时间复杂度:O(E) E:图中没有边

相关问题