解题思路
要求树的高度,可从起子树中的最大高度 + 1 解得
代码
#include<stdio.h>
#include<algorithm>
#include<vector>
using namespace std;
vector<int> child[1010];
int n;
int DFS(int root)
{
if(n == 1)
return 1;
if(child[root].size() == 0)
return 0;
int height = 1;
for (int i = 0; i < child[root].size(); i++)
{
height = max(height , DFS(child[root][i]));
}
return height + 1;
}
int main()
{
scanf("%d", &n);
int a, b;
for (int i = 0; i < n - 1; i++)
{
scanf("%d %d", &a, &b);
child[a].push_back(b);
}
int ans = DFS(1);
printf("%d\n", ans);
return 0;
}