二叉樹(dfs)

樣例輸入:
5        //下面n行每行有兩個數


2 3    //第i行的兩個數,代表編號爲i的節點所連接的兩個左右兒子的編號。


4 5


0 0    // 0 表示無


0 0


0 0
 


樣例輸出:

2 3 



#include<iostream>
#include<algorithm>
#define inf -1
using namespace std;
typedef pair <int,int> tp;
tp a[1000];
int w[1000]= {0};
int deep=0,wide=0;
void dfs(int s,int d)
{
    w[d]++;
    wide=max(wide,w[d]);
    deep=max(deep,d);
    if(a[s].first) dfs(a[s].first,d+1);
    if(a[s].second) dfs(a[s].second,d+1);
}
int main()
{
    int n;
    scanf("%d",&n);
    getchar();
    for (int i=1; i<=n; i++)
    {
        scanf("%d%d",&a[i].first,&a[i].second);
        getchar();
    }
    dfs(1,1);
    printf("%d %d",wide,deep);
    return 0;
}


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