CODE[VS] NO.1501 二叉树最大宽度和高度

来源:互联网 发布:备案域名 购买 编辑:程序博客网 时间:2024/05/16 22:36
题目描述 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


代码:

#include<iostream>#include<algorithm>#include<cstdio>#include<cstdlib>#include<cmath>#include<queue>#include<stack>#include<cstring>#include<set>#define INF 0x3f3f3f3f#define MAX 1000#define PI 3.1415926using namespace std;int main(){    int n;    cin >> n;    int arr[3][25];    //存储高度,hm和wm分别代表最大深度和宽度    int h[MAX] = {0}, w[MAX] = {0}, hm = 0, wm = 0;    //一定从1开始,记住!!!    h[1] = 1;    //arr[1][i] 和 arr[2][i]分别代表编号为i的两个子节点    for(int i = 1; i <= n; i++){        cin >> arr[1][i] >> arr[2][i];    }    //对应的子节点深度加1;若不懂可以将数组表示二叉树的编号写下来    for(int i = 1; i <= n; i++){        if(arr[1][i] != 0)            h[arr[1][i]] = h[i] + 1;        if(arr[2][i] != 0)            h[arr[2][i]] = h[i] + 1;    }    //每层深度出现一个节点,对应宽度都应加1    for(int i = 1; i <= n; i++){        hm = max(hm, h[i]);        w[h[i]] += 1;    }    for(int i = 1; i <= n; i++){        wm = max(wm, w[i]);    }    cout << wm << ' ' << hm << endl;    return 0;}


0 0