找出二叉树的最大宽度和最大深度

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

输入描述 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

#include <iostream>

using namespace std;

struct tree{
	int l;
	int r;
};

tree t[17];

int max_high(int n){
	if(n != 0 ){
		int l_high=max_high(t[n].l);
		int r_high=max_high(t[n].r);
		return l_high > r_high? (l_high+1) : (r_high+1);
	}
	else return 0; 
}//找出最大深度 

int GetWidth(int n,int k)
{
	if(n == 0) return 0;
	if(k==1) return 1;
	int numl=GetWidth(t[n].l,k-1);
	int numr=GetWidth(t[n].r,k-1);
	return (numl+numr);
}//找出第k层的宽度 
int main()
{
	
	int n;
	cin >> n;
	for(int i=1; i <= n; ++i)
	{
		int L,R;
		cin >> L >> R;
		t[i].l=L;
		t[i].r=R; 
	}
	int max_dep = max_high(1);
	int max_wid;
	for(int i=1; i <= max_dep; ++i){
		if(i==1) max_wid=GetWidth(1,i);
		else{
			max_wid=max_wid<GetWidth(1,i)?GetWidth(1,i):max_wid;
		}
	}//通过循环找出每一层的宽度并进行比较 
	cout << max_wid << " " << max_dep << endl;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值