You have n nodes, numbered 0 to n - 1, and a list of undirected connections edges, where edges[i] = [a, b] links node a and node b in both directions.
Return true if the nodes and edges together form a tree, and false otherwise. A tree has two properties at once:
Five edges join all six nodes, and none of them closes a loop.
Every node is reachable, but 1 → 2 → 3 → 1 is a cycle.
There is no cycle, but node 3 touches no edge and {0, 4} cannot reach {1, 2}: the nodes fall into separate pieces.
Constraints
1 <= n <= 20000 <= edges.length <= 5000edges[i].length == 20 <= a, b < n and a != bA tree on n nodes always has exactly n - 1 edges. Once the count is right, being connected and having no cycle each imply the other, so check the count and then only one of the two.
A tree has to pass two checks at once: every node reachable, and no loop. Each check alone is easy to get right and wrong to stop at. Example 3 has no loop but falls apart into pieces. A triangle plus one lonely node is the opposite case.
Time O(n log n)Space O(n)
The full walkthrough and code are part of Premium
true