給出一個二叉樹,輸出它的最大寬度和高度。
第一行一個整數n。
下面n行每行有兩個數,對於第i行的兩個數,代表編號爲i的節點所連接的兩個左右兒子的編號。如果沒有某個兒子爲空,則爲0。
輸出共一行,輸出二叉樹的最大寬度和高度,用一個空格隔開。
5
2 3
4 5
0 0
0 0
0 0
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;
}