codevs1501 二叉树最大宽度和高度

题目描述 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<algorithm>
using namespace std;
struct Node{int dep,L,R;}a[1000];
int W[1000],D=0;

void DFS(int i,int d){
	W[d]++;
	D=max(D,d);
	if(a[i].L)DFS(a[i].L,d+1);
	if(a[i].R)DFS(a[i].R,d+1);
}
int main(){ int n,i; scanf("%d",&n); for(i=1;i<=n;i++)scanf("%d%d",&a[i].L,&a[i].R); DFS(1,1); printf("%d %d ",*max_element(W+1,W+D+1),D); return 0; }

原文地址:https://www.cnblogs.com/codetogether/p/7066340.html