您的位置:首页 > 编程语言 > C语言/C++

C++学习笔记(二十四)笔试编程题整理

2018-03-26 19:31 369 查看
一、题目描述
现在有一棵合法的二叉树,树的节点都是用数字表示,现在给定这棵树上所有的父子关系,求这棵树的高度
输入描述:
输入的第一行表示节点的个数n(1 ≤ n ≤ 1000,节点的编号为0到n-1)组成,
下面是n-1行,每行有两个整数,第一个数表示父节点的编号,第二个数表示子节点的编号
输出描述:
输出树的高度,为一个整数

示例1
输入

5
0 1
0 2
1 3
1 4
输出
3#include <iostream>
#include <vector>
using namespace std;

int degree(vector< vector<int> > &tree, int node)
{
int size = tree[node].size();

if (size == 0) // 孩子节点个数为0 return 1
return 1;

if (size == 1) // 只有一个孩子节点 那个孩子的高度 + 1
return degree(tree, tree[node][0])+1;
else // 如果有两个孩子节点 先算出两个孩子的高度 比较高的那个孩子高度+1
{
int left = degree(tree, tree[node][0]);
int right = degree(tree, tree[node][1]);
return (left>right?left+1:right+1);
}
}

int main()
{
int n;
cin >> n;
vector< vector<int> > tree(n);

for (int i = 0; i < n-1; i++)
{
int parent;
int child;
cin >> parent >> child;
tree[parent].push_back(child);
}

cout << degree(tree, 0) << endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: