# Graph Valid Tree in C++

C++Server Side ProgrammingProgramming

Suppose we have n nodes they are labeled from 0 to n-1 and a list of undirected edges [u,v], We have to define a function to check whether these edges make up a valid tree or not.

So, if the input is like n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]], then the output will be true

To solve this, we will follow these steps −

• Define a function dfs(), this will take node, par, graph, and another array called visited,

• if visited[node] is same as 1, then −

• return true

• if visited[node] is same as 2, then −

• return false

• visited[node] := 2

• ret := true

• for initialize i := 0, when i < size of graph[node], update (increase i by 1), do −

• if graph[node, i] is not equal to par, then −

• ret := ret AND dfs(graph[node, i], node, graph, visited)

• visited[node] := 1

• return ret

• From the main method do the following −

• Define an array visited of size n and fill this with 0.

• Define a list of lists called graph of size n

• for initialize i := 0, when i < size of edges, update (increase i by 1), do −

• u := edges[i, 0], v := edges[i, 1]

• insert v at the end of graph[u]

• insert u at the end of graph[v]

• if dfs(0, -1, graph, visited) is false, then −

• return false

• for initialize i := 0, when i < n, update (increase i by 1), do −

• if visited[i] is zero, then −

• return false

• return true

## Example

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
bool dfs(int node, int par, vector <int< graph[], vector <int<& visited){
if (visited[node] == 1)
return true;
if (visited[node] == 2)
return false;
visited[node] = 2;
bool ret = true;
for (int i = 0; i < graph[node].size(); i++) {
if (graph[node][i] != par)
ret &= dfs(graph[node][i], node, graph, visited);
}
visited[node] = 1;
return ret;
}
bool validTree(int n, vector<vector<int<>& edges) {
vector<int< visited(n, 0);
vector<int< graph[n];
for (int i = 0; i < edges.size(); i++) {
int u = edges[i];
int v = edges[i];
graph[u].push_back(v);
graph[v].push_back(u);
}
if (!dfs(0, -1, graph, visited))
return false;
for (int i = 0; i < n; i++) {
if (!visited[i])
return false;
}
return true;
}
};
main(){
Solution ob;
vector<vector<int<> v = {{0,1},{0,2},{0,3},{1,4}};
cout << (ob.validTree(5,v));
}

## Input

5, {{0,1},{0,2},{0,3},{1,4}}

## Output

1