给出一个二叉树,输出它的最大宽度和高度。
输入描述 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>
#include <queue>
#include<algorithm>
using namespace std;
int a[17][3];
int width = 0;
queue<int> qu;
int maxtree(int n)
{
if (a[n][1] == 0 && a[n][2] == 0)
return 1;
if (a[n][1] != 0 && a[n][2] == 0)
return 1 + maxtree(a[n][1]);
if (a[n][1] == 0 && a[n][2] != 0)
return 1 + maxtree(a[n][2]);
return max(maxtree(a[n][1]), maxtree(a[n][2])) + 1;
}
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> a[i][1] >> a[i][2];
}
qu.push(1);
while (true)
{
int len = qu.size();
if (qu.size()>with)
{
width = qu.size();
}
if (len==0)
{
break;
}
while (len>0)
{
int x = qu.front();
qu.pop();
len--;
if (a[x][1]!=0)
{
qu.push(a[x][1]);
}
if (a[x][2] != 0)
{
qu.push(a[x][2]);
}
}
}
cout << width<<" ";
cout << maxtree(1);
//cin >> n;
return 0;
}