random_tree#

random_tree(n, seed=None, create_using=None)[source]#

Returns a uniformly random tree on n nodes.

Parameters:
nint

A positive integer representing the number of nodes in the tree.

seedinteger, random_state, or None (default)

Indicator of random number generation state. See Randomness.

create_usingNetworkX graph constructor, optional (default=nx.Graph)

Graph type to create. If graph instance, then cleared before populated.

Returns:
NetworkX graph

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

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.

Examples

>>> tree = nx.random_tree(n=10, seed=0)
>>> nx.write_network_text(tree, sources=[0])
╙── 0
    β”œβ”€β”€ 3
    └── 4
        β”œβ”€β”€ 6
        β”‚   β”œβ”€β”€ 1
        β”‚   β”œβ”€β”€ 2
        β”‚   └── 7
        β”‚       └── 8
        β”‚           └── 5
        └── 9
>>> tree = nx.random_tree(n=10, seed=0, create_using=nx.DiGraph)
>>> nx.write_network_text(tree)
╙── 0
    β”œβ”€β•Ό 3
    └─╼ 4
        β”œβ”€β•Ό 6
        β”‚   β”œβ”€β•Ό 1
        β”‚   β”œβ”€β•Ό 2
        β”‚   └─╼ 7
        β”‚       └─╼ 8
        β”‚           └─╼ 5
        └─╼ 9