【发布时间】:2015-09-13 08:22:57
【问题描述】:
我以深度优先的方式遍历树的节点。假设树如下:
现在,假设我在节点 E 中,并且在某些情况下我想回到节点 C 并从那里继续。然后应该取消之前的遍历并且应该再次评估节点C、D、E。节点F 和G 不应被遍历两次,因为之前的递归导航已被取消!
Usual navigation : A B C D E F G
The desire navigation : A B C D E C D E F G
深度优先遍历的一般代码如下:
void DFS(node x)
{
z = evaluate(x);
// if (z != null) DFS(z)
// Z could be a node which has been already traversed,
// let's suppose it's an ancestor of x
foreach (node y in c.children)
{
DFS(y);
}
}
请帮助我如何在树中进行这样的导航?
【问题讨论】:
-
您能否再解释一下,声明中并不清楚。您正在做 DFS,并且您现在在某个节点访问了一些节点,您评估了一些东西,为此您想重新评估上一级中的节点?
-
@Anup 是的,我应该取消递归并返回一个节点并继续从那里遍历
-
好的,这意味着如果我在 E 中评估了某些东西,那么我必须重做 C、D、E、F,而对于 A,它会继续原样吗?
-
z是否总是x的祖先(因为它会用于,例如,循环取消)? -
@Ahmad Clear it man if you hit something at E then as you didn't evaluate F and G so you are not going to evaluate them and you will evaluate all the previous nodes but only on the current level因为你没有提到重新评估B或A。?是吗?