261. Graph Valid Tree
Explanation:
To determine if a given graph is a valid tree, we need to check two conditions:
- The graph is fully connected (no isolated nodes).
- The graph has no cycles.
We can solve this problem using a depth-first search (DFS) algorithm. We will start the DFS traversal from any node and visit all its neighbors. While visiting each neighbor, we will mark the current node as visited. If we encounter a visited node, it means there is a cycle in the graph. Additionally, we will keep track of the number of connected components in the graph. If there is more than one connected component, the graph is not a valid tree.
: :
class Solution {
public boolean validTree(int n, int[][] edges) {
List<List<Integer>> adjList = new ArrayList<>();
for (int i = 0; i < n; i++) {
adjList.add(new ArrayList<>());
}
for (int[] edge : edges) {
adjList.get(edge[0]).add(edge[1]);
adjList.get(edge[1]).add(edge[0]);
}
boolean[] visited = new boolean[n];
if (hasCycle(-1, 0, visited, adjList)) {
return false;
}
for (boolean v : visited) {
if (!v) {
return false;
}
}
return true;
}
private boolean hasCycle(int parent, int node, boolean[] visited, List<List<Integer>> adjList) {
visited[node] = true;
for (int neighbor : adjList.get(node)) {
if (!visited[neighbor]) {
if (hasCycle(node, neighbor, visited, adjList)) {
return true;
}
} else if (neighbor != parent) {
return true;
}
}
return false;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.