C++
$\color{gold}{— > 蓝桥杯辅导课题解}$
思路:
贪心 DFS
$节点的最大高度 = 子节点的数量 + 子节点所能形成的最大深度$
$code1:$
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n;
int h[N], e[N], ne[N], idx;
void add(int a, int b) {
e[idx] = b, ne[idx] = h[a], h[a] = idx ++;
}
int dfs(int u) {
int hmax = 0, cnt = 0; // cnt:子节点的数量 hmax:子节点所能形成的最大深度
for (int i = h[u]; ~i; i = ne[i]) {
int j = e[i];
hmax = max(hmax, dfs(j));
cnt ++;
}
return hmax + cnt;
}
int main() {
cin >> n;
memset(h, -1, sizeof h);
for (int i = 2; i <= n; i ++) {
int p; cin >> p;
add(p, i); // 在邻接表中加入父节点和当前点的边
}
cout << dfs(1);
return 0;
}
$code2:$
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n;
vector<int> g[N];
int dfs(int u) {
int ans = 0, cnt = g[u].size();
for (int i = 0; i < cnt; i ++)
ans = max(ans, dfs(g[u][i]) + cnt);
return ans;
}
int main() {
cin >> n;
for (int i = 2; i <= n; i ++) {
int x; cin >> x;
g[x].push_back(i);
}
cout << dfs(1);
return 0;
}