Advertisement
pb_jiang

LC1245 AC2

Jan 15th, 2023
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.53 KB | None | 0 0
  1. class Solution {
  2.     int ans = 0;
  3.     vector<int> g[10003];
  4.     int dfs(int u, int fa) {
  5.         int a = -1;
  6.         for (auto v: g[u]) {
  7.             if (v == fa) continue;
  8.             int val = dfs(v, u);
  9.             ans = max(ans, a + 1 + val + 1);
  10.             a = max(a, val);
  11.         }
  12.         a += 1;
  13.         return a;
  14.     }
  15. public:
  16.     int treeDiameter(vector<vector<int>>& edges) {
  17.         for (const auto& e: edges) g[e[0]].push_back(e[1]), g[e[1]].push_back(e[0]);
  18.         dfs(0, -1);
  19.         return ans;
  20.     }
  21. };
  22.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement