Fetch connected nodes in a NetworkX graph

You can simply use a Breadth-first search starting from your given node or any node.

In Networkx you can have the tree-graph from your starting node using the function:

bfs_tree(G, source, reverse=False)

Here is a link to the doc: Network bfs_tree.


Assuming the graph is undirected, there is a built-in networkx command for this:

node_connected_component(G, n)

The documentation is here. It returns all nodes in the connected component of G containing n.

It's not recursive, but I don't think you actually need or even want that.


comments on your code: You've got a bug that will often result an infinite recursion. If u and v are neighbors both with degree at least 2, then it will start with u, put v in the list and when processing v put u in the list and keep repeating. It needs to change to only process neighbors that are not in neighbors_list. It's expensive to check that, so instead use a set. There's also a small problem if the starting node has degree 1. Your test for degree 1 doesn't do what you're after. If the initial node has degree 1, but its neighbor has higher degree it won't find the neighbor's neighbors.

Here's a modification of your code:

def fetch_connected_nodes(G, node, seen = None):
    if seen == None:
        seen = set([node])
    for neighbor in G.neighbors(node):
        print(neighbor)
        if neighbor not in seen:
            seen.add(neighbor)
            fetch_connected_nodes(G, neighbor, seen)
    return seen

You call this like fetch_connected_nodes(assembly, starting_node).