dfs_preorder_nodes(G, source=None, depth_limit=None, *, sort_neighbors=None)[source]#

Generate nodes in a depth-first-search pre-ordering starting at source.

GNetworkX graph
sourcenode, optional

Specify starting node for depth-first search and return nodes in the component reachable from source.

depth_limitint, optional (default=len(G))

Specify the maximum search depth.

sort_neighborsfunction (default=None)

A function that takes an iterator over nodes as the input, and returns an iterable of the same nodes with a custom ordering. For example, sorted will sort the nodes in increasing order.

nodes: generator

A generator of nodes in a depth-first-search pre-ordering.


If a source is not specified then a source is chosen arbitrarily and repeatedly until all components in the graph are searched.

The implementation of this function is adapted from David Eppstein’s depth-first search function in PADS, with modifications to allow depth limits based on the Wikipedia article “Depth-limited search”.


>>> G = nx.path_graph(5)
>>> list(nx.dfs_preorder_nodes(G, source=0))
[0, 1, 2, 3, 4]
>>> list(nx.dfs_preorder_nodes(G, source=0, depth_limit=2))
[0, 1, 2]