版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Wchenchen0/article/details/82791613
题目描述
一棵树有n个节点,其中1号节点为根节点。
输入
第一行是整数n,表示节点数
后面若干行,每行两个整数a b,表示b是a的子节点。
输出
求这棵树的高度(根节点为第1层)
样例输入
5 1 2 1 3 3 4 3 5
样例输出
3
这题就是单纯的练习如果不是二叉树,那么该如何求解的问题,这里用到了树的静态写法,但是如果是二叉树用链表还是很舒服的。
#include<iostream>
#include<string>
#include<map>
#include<vector>
#include<queue>
using namespace std;
const int N = 1e6 + 10;
struct node
{
int data;
vector<int>p;
int layer;
}s[N];
int flag;
void la(int x)
{
queue<int>Q;
Q.push(x);
while (!Q.empty()) {
int now = Q.front();
Q.pop();
for (int i = 0;i < s[now].p.size();i++) {
int child = s[now].p[i];
Q.push(child);
s[child].layer = s[now].layer + 1;
if (flag < s[child].layer) flag = s[child].layer;
}
}
}
int main()
{
int n;
while (scanf("%d", &n) == 1) {
flag = 0;
for (int i = 0;i < n - 1;i++) {
int a, b;
scanf("%d %d", &a, &b);
s[a].p.push_back(b);
}
s[1].layer = 1;
la(1);
printf("%d\n", flag);
}
return 0;
}