How should I go about checking for infinite loops in a nodemap

I am making a nodemap system and am implementing a function to check when connecting 2 nodes if the node would yield infinitely, how would I go about doing this in the best way possible?

Good

Bad
image

I basically want to check if the nodes run back into each other anywhere in the line

Each point on each node has an object value of the connecting points node

something like this?

local node1 = --node1
local node2 = node1.ConnectingNode.Value

if node2.ConnectingNode.Value == node1 then
    print("Looping nodes")
end

I ended up making a function that would trace back all of the branches from the current node with separate threads to run simultaneously and if the function found the node your trying to connect to it would deny the connection if it was not found then it would allow the connection