diameter of tree using dfs

Solutions on MaxInterview for diameter of tree using dfs by the best coders in the world

showing results for - "diameter of tree using dfs"
Alisha
22 Aug 2016
1#include <bits/stdc++.h>
2using namespace std;
3#define pb push_back
4class Solution {
5public:
6   map <int ,int > l;
7   int best;
8   int node;
9   int dfs(int v, bool* visited, vector <int> graph[], int c = 0){
10      visited[v] = true;
11      int ans = 0;
12      for(int i = 0; i < graph[v].size(); i++){
13         if(!visited[graph[v][i]])ans = max(ans,dfs(graph[v][i], visited, graph, c+1));
14      }
15      if(c > best){
16         best = c;
17         node = v ;
18      }
19      visited[v] = false;
20      return max(c,ans);
21   }
22   int treeDiameter(vector<vector<int>>& e) {
23      int n = e.size();
24      vector <int> graph[n+1];
25      for(int i = 0; i < n; i++){
26         graph[e[i][0]].pb(e[i][1]);
27         graph[e[i][1]].pb(e[i][0]);
28      }
29      bool* visited = new bool[n+1]();
30      best = 0;
31      node = 0;
32      dfs(0, visited, graph);
33      bool* visited2 = new bool[n+1]();
34      return dfs(node, visited2, graph);
35   }
36};
37main(){
38   vector<vector<int>> v = {{0,1},{1,2},{2,3},{1,4},{4,5}};
39   Solution ob;
40   cout <<ob.treeDiameter(v);
41}