Graph Valid Tree

You are given n nodes labelled 0 to n - 1 and a list of undirected edges, where edges[i] = [a, b] joins nodes a and b.

Return true if these edges form a valid tree, and false otherwise. A valid tree must be:

  • connected: every node can reach every other node, and
  • acyclic: there is no way to leave a node and come back to it without reusing an edge.

A single node with no edges is a valid tree.

Constraints

  • 1 <= n <= 2000
  • 0 <= edges.length <= 5000
  • 0 <= a, b < n and a !== b
  • No edge appears twice.

Examples

Example 1

Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
Output: true

Four edges for five nodes, no cycle, and every node is reachable from 0: a tree.

Example 2

Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
Output: false

1-2-3-1 is a cycle, so this is not a tree (it also has 5 edges, one too many).

Example 3

Input: n = 4, edges = [[0,1],[1,2],[2,0]]
Output: false

Three edges is the right count for four nodes, but they form a triangle and node 3 is left on its own.

JavaScript you'll use: Classes for data structures Arrays: create, read, update

/**
 * @param {number} n
 * @param {number[][]} edges
 * @return {boolean}
 */
function validTree(n, edges) {
  
}

Ctrl/⌘ + ' runs the examples, Ctrl/⌘ + Enter submits. Use console.log freely: output shows under Console. In the editor, press Esc then Tab to move focus out.