题目描述:
现在有一棵合法的二叉树,树的节点都是用数字表示,现在给定这棵树上所有的父子关系,求这棵树的高度
输入描述:
输入的第一行表示节点的个数n(1 ≤ n ≤ 1000,节点的编号为0到n-1)组成, 下面是n-1行,每行有两个整数,第一个数表示父节点的编号,第二个数表示子节点的编号
输出描述:
输出树的高度,为一个整数
示例1:
输入
5 0 1 0 2 1 3 1 4
输出
3
解题思路:
需要注意的一点是并不是所有的父节点都是存在的,而且输入可能一个父节点超过两个子节点,当父节点的子节点超过两个时可以不同去管,在这里可以用一个vector动态数组表示节点对应的高度,一个vector动态数组表示父节点的子节点树
代码:
#include <iostream>
#include <vector>
using namespace std;
int main() {
int Height = 1;
int row;
int father, son;
cin >> row;
vector<int> nodes(1000, 0); //用来存放不同节点的高度
nodes[0] = 1; //至少有一个节点0,其高度是1
vector<int> childnum(1000, 0); //用来存放每一个节点的子节点个数
for (int i = 1; i < row; i++) {
cin >> father >> son;
if (nodes[father] == 0 || childnum[father] == 2)
continue; //如果父节点不存在或者是父节点有两个子节点了那么就跳过
childnum[father] += 1; //子节点数量加一
nodes[son] = nodes[father] + 1; //子节点的高度是父节点高度加一
if (nodes[son] > Height)
Height = nodes[son]; //用来保存最大的高度
}
cout << Height << endl;
}