Warning

This documents an unmaintained version of NetworkX. Please upgrade to a maintained version and see the current NetworkX documentation.

networkx.generators.trees.random_tree

random_tree(n, seed=None)[source]

Returns a uniformly random tree on n nodes.

Parameters:
  • n (int) – A positive integer representing the number of nodes in the tree.
  • seed (integer, random_state, or None (default)) – Indicator of random number generation state. See Randomness.
Returns:

A tree, given as an undirected graph, whose nodes are numbers in the set {0, …, n - 1}.

Return type:

NetworkX graph

Raises:

NetworkXPointlessConcept – If n is zero (because the null graph is not a tree).

Notes

The current implementation of this function generates a uniformly random Prüfer sequence then converts that to a tree via the from_prufer_sequence() function. Since there is a bijection between Prüfer sequences of length n - 2 and trees on n nodes, the tree is chosen uniformly at random from the set of all trees on n nodes.