1004 Counting Leaves (30 分)求树高和树叶子宽,几乎都是那几句话

这些问题都差不多,dfs那几条语句有的放在判断内,有的放在判断外不同

#include<iostream>
#include<vector>
using namespace std;
struct node{
    
    
    vector<int>  child;
}n[101];
int N,m,d[101]={
    
    0},maxd=0;
void dfs(int root,int depth){
    
    
    if(n[root].child.size()==0)
    {
    
    
        d[depth]++;
        if(depth>maxd)
            maxd=depth;
    }
    else{
    
    
        for(int i=0;i<n[root].child.size();i++)
            dfs(n[root].child[i],depth+1);
    }
}
int main(){
    
    
    cin>>N>>m;
    for(int i=0;i<m;i++){
    
    
        int temp,num,t;
        cin>>temp>>num;
        for(int j=0;j<num;j++)
        {
    
    
            cin>>t;
            n[temp].child.push_back(t);
        }
    }
    dfs(1,0);
    cout<<d[0];
    for(int i=1;i<=maxd;i++)
        cout<<" "<<d[i];
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42835526/article/details/113716375