【PAT1004】-Counting Leaves

实现思路

题目大意就是计算出树的每一层中叶节点的个数

(一)建树

  1. 构建树的节点
    这一步决定了节点和节点之间的连接关系,在本体中没有提到树是二叉树,所以孩子节点的存储依靠vector存储,为方便存储在里面存放的是节点的id号

  2. 存储所有树的节点
    由于存储的孩子是id号,且本题中树的个数不超过100,那么直接创建一个105大小的树节点指针的数组,数组的下标正好对应树节点的id号

  3. 正常读取数据建树即可
    (二)遍历
    这里面遍历正常使用递归遍历即可,在遍历的过程中传递层数这一参数,当该节点为叶节点在本层记录叶节点个数的变量+1,否则遍历其子节点,在遍历子节点时修改层数为本层数+1
    (三)打印结果

实现代码

#include <cstdio>
#include <iostream>
#include <vector>
#include <queue>
#include <utility>
using namespace std;

int n,m;
struct TreeNode{
    
    
  int val;
  vector<int> child;
  TreeNode(int val){
    
    
      this->val=val;
  }
};
const int maxn=100+5;
TreeNode *tree[maxn];
int count[maxn];
int max_depth;
void init(){
    
    
    max_depth=0;
    for(int i=0;i<n;i++){
    
    
        count[i]=0;
        TreeNode *t=new TreeNode(i+1);
        tree[i+1]=t;
    }
}

void get_count(TreeNode *root,int depth){
    
    
    
    if(depth>max_depth) {
    
    
        max_depth=depth;
    }
    
    if(root->child.size()==0){
    
    
        count[depth]++;
    }
    else{
    
    
     for(int i=0;i<root->child.size();i++){
    
    
         get_count(tree[root->child[i]],depth+1);
     }   
    }
}
int main(){
    
    
    while(scanf("%d%d",&n,&m)==2&&n){
    
    
        init();
        for(int i=0;i<m;i++){
    
    
            int id,k;
            scanf("%d%d",&id,&k);
            for(int j=0;j<k;j++){
    
    
                int vt;
                scanf("%d",&vt);
                tree[id]->child.push_back(vt);
            }
        }
        get_count(tree[1],0);
        for(int i=0;i<=max_depth;i++){
    
    
            if(i) cout<<" ";
            cout<<count[i];
        }
    }
    return 0;
}

提交结果及分析

在这里插入图片描述时间复杂度O(n)

猜你喜欢

转载自blog.csdn.net/weixin_44944046/article/details/114459957