1018. Check if Graph is Tree

EasyGraphsBFSDSUGraph

Given an undirected graph with n nodes and a list of edges, determine whether it forms a tree — connected and acyclic (equivalently, connected with exactly n-1 edges). Return true or false. The input is JSON {n, edges}.

Input: JSON {n, edges}.

Output: Boolean — true or false.

Examples

Example 1
Input: {"n":4,"edges":[[0,1],[0,2],[0,3]]}
Output: true
Explanation: Connected and acyclic.
Example 2
Input: {"n":4,"edges":[[0,1],[1,2],[2,0]]}
Output: false
Explanation: Has a cycle and is disconnected.
Example 3
Input: {"n":1,"edges":[]}
Output: true
Explanation: A single node is a tree.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →