Given an undirected graph, find out if it is a tree.
A tree is an undirected graph in which there is exactly one path between any two vertices. In other word, the graph is both acyclic and connected.
Input
You can take input in any reasonable format. Here are some example formats:
- an adjacency matrix, e.g.,
[[0,1,1,0],[1,0,1,1],[1,1,0,0],[0,1,0,0]]
; - an adjacency list, e.g.,
{1:[2,3],2:[1,3,4],3:[1,2],4:[2]}
; - an edge list, e.g.,
[(1,2),(1,3),(2,3),(2,4)]
; - a built-in graph object, e.g.,
Graph[{1,2,3,4},{1<->2,1<->3,2<->3,2<->4}]
in Mathematica.
All the above examples represent the following graph, which is not a tree:
1---2---4
\ /
3
Here I use numbers 1,2,3,4
to represent the vertices. You may also use, for example, 0,1,2,3
.
You may assume that:
- The graph is non-empty.
- The graph has no loop (an edge connecting a vertex with itself) or multi-edge (two or more edges that connect the same two vertices).
- Each vertex is connected to at least one other vertex.
Output
A value representing whether the graph is a tree. You can choose to
- output truthy/falsy using your language's convention (swapping is allowed), or
- use two distinct, fixed values to represent true (affirmative) or false (negative) respectively.
This is code-golf, so the shortest code in bytes wins.
Testcases
Here I take inputs as edge lists.
Truthy
[(1, 2)]
[(1, 2), (2, 3), (2, 4)]
[(1, 2), (2, 3), (3, 4), (4, 5)]
[(1, 2), (1, 3), (2, 4), (2, 5)]
[(1, 3), (1, 6), (1, 7), (2, 3), (2, 5), (4, 7)]
Falsy
[(1, 2), (3, 4)]
[(1, 2), (1, 3), (2, 3), (2, 4)]
[(1, 2), (1, 3), (2, 3), (4, 5)]
[(1, 3), (1, 5), (2, 3), (3, 4), (4, 5)]
[(1, 2), (3, 4), (3, 5), (4, 5), (4, 7), (6, 7)]