Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an undirected graph is a tree in networkx

I would like to know if there is a simple way to check whether a certain undirected graph in networkx is a tree or not

like image 760
papafe Avatar asked May 18 '13 18:05

papafe


2 Answers

The fastest way for a graph G(V,E) might be to check if |V| = |E| + 1 and that G is connected:

import networkx as nx
def is_tree(G):
    if nx.number_of_nodes(G) != nx.number_of_edges(G) + 1:
        return False
    return nx.is_connected(G)

if __name__ == '__main__':

    print(is_tree(nx.path_graph(5)))
    print(is_tree(nx.star_graph(5)))
    print(is_tree(nx.house_graph()))
like image 190
Aric Avatar answered Sep 30 '22 06:09

Aric


There are built-in functions in networkx to check the type of a given graph.

To check if it's a tree, run networkx.is_tree(g). See algorithms for trees in networkx documentation.

like image 37
Edward Avatar answered Sep 30 '22 06:09

Edward