1501 二叉树最大宽度和高度
时间限制: 1 s
空间限制: 128000 KB
题目等级 : 白银 Silver
题解
题目描述 Description
给出一个二叉树,输出它的最大宽度和高度。
输入描述 Input Description
第一行一个整数n。
下面n行每行有两个数,对于第i行的两个数,代表编号为i的节点所连接的两个左右儿子的编号。如果没有某个儿子为空,则为0。
输出描述 Output Description
输出共一行,输出二叉树的最大宽度和高度,用一个空格隔开。
样例输入 Sample Input
5
2 3
4 5
0 0
0 0
0 0
样例输出 Sample Output
2 3
数据范围及提示 Data Size & Hint
n<16
默认第一个是根节点
以输入的次序为编号
2-N+1行指的是这个节点的左孩子和右孩子
注意:第二题有极端数据!
1
0 0
时间限制: 1 s
空间限制: 128000 KB
题目等级 : 白银 Silver
题解
题目描述 Description
给出一个二叉树,输出它的最大宽度和高度。
输入描述 Input Description
第一行一个整数n。
下面n行每行有两个数,对于第i行的两个数,代表编号为i的节点所连接的两个左右儿子的编号。如果没有某个儿子为空,则为0。
输出描述 Output Description
输出共一行,输出二叉树的最大宽度和高度,用一个空格隔开。
样例输入 Sample Input
5
2 3
4 5
0 0
0 0
0 0
样例输出 Sample Output
2 3
数据范围及提示 Data Size & Hint
n<16
默认第一个是根节点
以输入的次序为编号
2-N+1行指的是这个节点的左孩子和右孩子
注意:第二题有极端数据!
1
0 0
这题你们别想投机取巧了,给我老老实实搜索!
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
int MaxHeight = 0;
int Height = 0;
int treeNode[16][2] = { 0 };
int num[16] = { 0 };
struct Node//树节点
{
int data;
int height;
Node* left;
Node* right;
};
typedef struct Node* Tree;
Tree Build(int x, Tree &t)//根据数组建树
{
if (x == 0)
{
t = NULL;
}
else
{
Height++;
if (Height > MaxHeight)
MaxHeight = Height;
t = (Tree)malloc(sizeof(Node));
t->data = x;
t->height = Height;
Build(treeNode[x][0], t->left);
Build(treeNode[x][1], t->right);
Height--;
}
return t;
}
void view(Tree &t)
{
if (t == NULL)
return;
else
{
view(t->left);
num[t->height]++;
view(t->right);
}
}
int main()
{
int n;
while (scanf("%d", &n) != EOF)
{
memset(num, 0, sizeof(int) * 16);
MaxHeight = 0;
Height = 0;
int findRoot[16] = { 0 };
int i,maxNum=0;
for (i = 1; i <= n; ++i)
{
scanf("%d%d", &treeNode[i][0], &treeNode[i][1]);
findRoot[treeNode[i][0]] = 1;
findRoot[treeNode[i][1]] = 1;
}
for (i = 1; i <= n; i++)
{
if (findRoot[i] == 0)
break;
}
Tree t;
t = Build(i, t);
view(t);
for (i = 1; i <= n; i++)
{
if (num[i] > maxNum)
maxNum = num[i];
}
printf("%d %d\n", maxNum, MaxHeight);
}
}