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