LeetCode Solutions

261. Graph Valid Tree

Time: $O(n)$

Space: $O(n)$

			

class Solution {
 public:
  bool validTree(int n, vector<vector<int>>& edges) {
    if (n == 0 || edges.size() != n - 1)
      return false;

    vector<vector<int>> graph(n);
    queue<int> q{{0}};
    unordered_set<int> seen{{0}};

    for (const vector<int>& e : edges) {
      const int u = e[0];
      const int v = e[1];
      graph[u].push_back(v);
      graph[v].push_back(u);
    }

    while (!q.empty()) {
      const int u = q.front();
      q.pop();
      for (const int v : graph[u])
        if (!seen.count(v)) {
          q.push(v);
          seen.insert(v);
        }
    }

    return seen.size() == n;
  }
};
			

class Solution {
  public boolean validTree(int n, int[][] edges) {
    if (n == 0 || edges.length != n - 1)
      return false;

    List<Integer>[] graph = new List[n];
    Queue<Integer> q = new ArrayDeque<>(Arrays.asList(0));
    Set<Integer> seen = new HashSet<>(Arrays.asList(0));

    for (int i = 0; i < n; ++i)
      graph[i] = new ArrayList<>();

    for (int[] e : edges) {
      final int u = e[0];
      final int v = e[1];
      graph[u].add(v);
      graph[v].add(u);
    }

    while (!q.isEmpty()) {
      final int u = q.poll();
      for (final int v : graph[u])
        if (!seen.contains(v)) {
          q.offer(v);
          seen.add(v);
        }
    }

    return seen.size() == n;
  }
}
			

class Solution:
  def validTree(self, n: int, edges: List[List[int]]) -> bool:
    if n == 0 or len(edges) != n - 1:
      return False

    graph = [[] for _ in range(n)]
    q = deque([0])
    seen = {0}

    for u, v in edges:
      graph[u].append(v)
      graph[v].append(u)

    while q:
      u = q.popleft()
      for v in graph[u]:
        if v not in seen:
          q.append(v)
          seen.add(v)

    return len(seen) == n