求二叉树的最大深度和广度

#include <bits/stdc++.h>
using namespace std;

struct Node{
    int m;
    int l;
    int r;
}node[100];

int depth[100];

void first(int k,int d){
    depth[d++]++;
    if(node[k].l != 0)first(node[k].l,d);
    if(node[k].r != 0)first(node[k].r,d);
}

int main(){
    int n;
    cin >> n;
    for(int i = 1;i <= n;i++){
        cin >> node[i].l >> node[i].r;
        node[i].m = i;
    }
    first(1,1);
    int maxwide = -100;
    for(int i =1;i <= n;i++){
        if(depth[i] > maxwide) maxwide = depth[i];
    }
    cout << maxwide << " ";
    int i;
    for( i = 1;depth[i] != 0;i++) ;
    cout << i-1 ;
    return 0;
}

这个depth用的秒

#include "bits/stdc++.h"
using namespace std;

int a[1000];
int b[1000];

int width[100];
int maxdeep = 0;

void dfsdepth(int i,int depth)
{
    maxdeep = max(depth,maxdeep);
    width[depth]++;
//    if(a[i] == 0 && b[i] == 0)
//        return;
    if(a[i] != 0)
        dfsdepth(a[i],depth+1);  //一开始我用的是depth++,后来意识到递归不能这样,加1以后就是新的depth了
    if(b[i] != 0)
        dfsdepth(b[i],depth+1);  //shift + tab
}

int main()
{
    int n;
    int maxwidth = 0;          //if maxwidth is not given a initial number ,the ans will be 3. funny 
    cin >> n;
    for(int i=1;i <= n;i++)
        cin >> a[i] >> b[i];  //left && right can not be the name!!

    dfsdepth(1,1);

    for(int i=0;i < 100;i++)
        maxwidth = max(maxwidth,width[i]);

    cout << maxwidth << " " << maxdeep << endl;

    return 0;
}

用dfs搜索,啊啊啊啊啊啊啊啊,遇到了n多个bug好气啊,最后还是看答案写出来的,我好菜啊。

原文地址:https://www.cnblogs.com/cunyusup/p/7745791.html