CODE[VS] NO.1501 二叉樹最大寬度和高度

題目描述 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.1415926

using 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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章