Advertisement
pb_jiang

LC1245 AC

Jan 15th, 2023
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.66 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, b = -1;
  6.         for (auto v: g[u]) {
  7.             if (v == fa) continue;
  8.             int val = dfs(v, u);
  9.             if (val > a) b = a, a = val;
  10.             else if (val > b) b = val;
  11.         }
  12.         a += 1;
  13.         b += 1;
  14.         // cout << "u: " << u << " a: " << a << " b: " << b << endl;
  15.         ans = max(ans, a + b);
  16.         return a;
  17.     }
  18. public:
  19.     int treeDiameter(vector<vector<int>>& edges) {
  20.         for (const auto& e: edges) g[e[0]].push_back(e[1]), g[e[1]].push_back(e[0]);
  21.         dfs(0, -1);
  22.         return ans;
  23.     }
  24. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement