【天梯】递归-1501 二叉树最大宽度和高度

题目描述  Description

    给出一个二叉树,输出它的最大宽度和高度。

输入描述  Input Description

第一行一个整数n。

下面n行每行有两个数,对于第i行的两个数,代表编号为i的节点所连接的两个左右儿子的编号。如果没有某个儿子为空,则为0。

输出描述  Output Description

输出共一行,输出二叉树的最大宽度和高度,用一个空格隔开。

样例输入  Sample Input

5

2 3

4 5

0 0

0 0

0 0

扫描二维码关注公众号,回复: 1457895 查看本文章
样例输出  Sample Output

2 3

数据范围及提示  Data Size & Hint

n<16

默认第一个是根节点

以输入的次序为编号

2-N+1行指的是这个节点的左孩子和右孩子

注意:第二题有极端数据!

          1

          0 0

这题你们别想投机取巧了,给我老老实实搜索!

#include<iostream>
#include<algorithm>
using namespace std;
int l[50],r[50];
int a=0,t=1,b[15]={0},ans=0;

void dfs(int x,int y)
{
	if(x<=0){ans=max(ans,y);return;}
	
	if(l[x]>0){b[y]++;}
	if(r[x]>0){b[y]++;}
	a++;
	dfs(l[x],++y);
	y--;
	dfs(r[x],++y);
	y--;
}

int main()
{
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>l[i]>>r[i];
	}
	dfs(1,1);
	for(int i=1;i<=ans;i++)
	{
		t=max(b[i],t);
	}
	ans--;
	cout<<t<<' '<<ans;
	return 0;
} 


猜你喜欢

转载自blog.csdn.net/qq_36718092/article/details/80545874
今日推荐