def walk_links_for_node(node, callback, direction, obj=None):
    """
    Walks the each link from the given node. Raising a StopIteration will terminate the
    traversal.

    :type node: treestruct.Node
    :type callback: (treestruct.Node, treestruct.Node, object) -> ()
    :type direction: int
    :type obj: Any
    :return: Returns `obj` (or None if no `obj` is supplied).
    :rtype: Any
    """
    try:
        visited = set()
        queue = [node]
        while queue:
            node = queue.pop(0)
            if node in visited:
                continue
            visited.add(node)
            for connected_node in node.direction(direction):
                callback(node, connected_node, obj)
                queue.append(connected_node)
    except StopIteration:
        pass
    return obj
