您的位置:首页 > 其它

p1501 二叉树最大宽度和高度

2015-08-03 10:58 176 查看
题目描述 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<iostream>
using namespace std;
struct treetype{
int l,r;
};
int height[16]={0},weight[16]={0},maxheight=0,maxweight=0;
treetype tree[16];
void search(int x)
{
if (height[x]>maxheight)
maxheight=height[x];
if (weight[height[x]]>maxweight)
maxweight=weight[height[x]];
if (tree[x].l!=0)
{
height[tree[x].l]=height[x]+1;
weight[height[tree[x].l]]++;
search(tree[x].l);
}
if (tree[x].r!=0)
{
height[tree[x].r]=height[x]+1;
weight[height[tree[x].r]]++;
search(tree[x].r);
}
}
int main()
{
int n;
cin>>n;
for (int i=1;i<=n;i++)
cin>>tree[i].l>>tree[i].r;
height[1]=1;
weight[1]=1;
search(1);
cout<<maxweight<<' '<<maxheight;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  codevs_silver