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;
}
现在有一棵合法的二叉树,树的节点都是用数字表示,现在给定这棵树上所有的父子关系,求这棵树的高度
输入描述:
输入的第一行表示节点的个数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;
}
相关文章推荐
- 【C/C++学习笔记】memmove()、memcpy()、memccpy()、strcpy()函数整理
- [Boolan-C++学习笔记]第一周整理
- 2012年8月26日学习笔记---c++笔试题之一
- 【C++】学习笔记二十四——?:运算符
- c++学习笔记序列之错误码整理(不断更新中)
- [Boolan-C++学习笔记]第二周整理
- 2012年8月26日学习笔记---c++笔试题之二
- C++学习笔记二十四-Union
- 学习笔记问题大全【整理】1 C++
- C++课程学习笔记整理声明
- 设计模式C++学习笔记之十一(c/c++面试笔试题)
- MFC - HOOK和数据库访问 ( 孙鑫C++第二十讲笔记整理 )
- c++学习笔记之声明和定义的关系
- 学习笔记:C++ primer Plus chap5
- 算法学习笔记:排序算法整理
- C++虚函数和多态学习笔记
- C++学习笔记之类于对象
- c++学习笔记—单链表基本操作的实现
- STM32----学习笔记整理持续更新(GPIO、)
- 【C++学习笔记】如何将输出定向到txt