views:

117

answers:

2

Here is a tree:

  1. There will be one root.

  2. Each tree node has zero or more children.

  3. It is allowed that two nodes points to the same child. Say, both node A and node B has child C.

However, it is prohibited that,

Node A is an offspring of Node B, and Node B is an offspring of Node A.

One prohibited case is

Node A has a child Node C and Node D,

Both Node C and D has a child node E,

Node E has a child of A.

The question is, how to determine this circle in a fastest manner?

UPDATE: I realize this is to find any cycle in a directed graph. Just now I managed to think out a solution similar to Tarjan's algorithm.

Thanks for comments.

A: 

circles can be found using 2 pointers and advancing them at different intervals. Eventually the pointers will match, indicating a loop, or the "faster" one will reach then end. The question is usually asked of linked lists though, not trees.

No Refunds No Returns
I'm not sure this would be the *fastest manner* of doing it, but rather the *lowest memory overhead manner*. Also, it sounds complicated to do for a tree.
Hans W
The problem will be easy for a linked list. But consider this problem - the tree wil have multiple ends. Instead a linked list has only one end.
SiLent SoNG
yeah ... that's why I said the question is usually asked of lists, not trees. you'd have to run this for each node of the tree using a queue to remember the "next" nodes of each node as new starting points. It would be ugly.
No Refunds No Returns
+3  A: 

Do a Depth First Search through the tree. If at any point you find a node that is already in your backtracking stack, there is a circle.

David Schmitt
It will fail for this case: A->B, B->C, A->C
SiLent SoNG
sorry, that should have read "stack" instead of "parent. Fixed it.
David Schmitt
yeah, it works. thanks for answering.
SiLent SoNG