I’m still not very good with data structures, but I have this homework assignment that wants me to test if a tree-like structure is circular or not. That is when, in some form or another, the left and right pointers at a node end up pointing back to an earlier node.
I’ve been trying to come up with a recursive function for hours now, but I just can’t seem to get it. I don’t really have much work to show for it too.
Can someone give me some ideas on how I can go about doing this?
The language we are using is C.
Thanks.
Usually, the best way to do this is with depth first search (DFS). Start with the root node, mark it as “visited”, and start to follow the pointers. At each new node you reach, mark it as “visited”. If you reach a dead-end, back up and try another path.
If you ever follow a pointer and reach a node you already marked as visited, then you’ve got a cycle.
How about doing it recursively:
(warning: code may have bugs)