1004. Counting Leaves (30) 树的dfs

简介: #include #include #include using namespace std;//大意:统计每一层叶子结点的个数 并输出//根节点id固定为01//思路:树的模拟套路vector v[100]...
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
//大意:统计每一层叶子结点的个数 并输出
//根节点id固定为01
//思路:树的模拟套路

vector<int> v[100];
int level[100] = {0};
int maxdepth = 0;

void dfs(int index, int depth){//思路:遇到叶子结点就把level[depth]++
    if (v[index].size() == 0) {
        level[depth]++;
        if(depth > maxdepth) maxdepth = depth;
        return;
    }
    for (int i = 0; i < v[index].size(); i++) {
        dfs(v[index][i], depth + 1);
    }

}

int main(){
    int n, m;//结点个数  非非叶子结点的个数
    cin >> n >> m;
    for (int i = 0; i < m; i++) {
        int f, c;
        cin >> f >> c;
        for (int i = 0; i < c; i++) {
            int k;
            cin >> k;
            v[f].push_back(k);//f是k的父结点
        }
    }
    dfs(1, 0);
    for (int i = 0; i <= maxdepth; i++) {
        printf("%d%c", level[i], i == maxdepth ? '\n' : ' ');
    }

    return 0;
}
目录
相关文章
LeetCode 429. N-ary Tree Level Order Traversal
给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。
56 0
LeetCode 429. N-ary Tree Level Order Traversal
LeetCode 104. 二叉树的最大深度 Maximum Depth of Binary Tree
LeetCode 104. 二叉树的最大深度 Maximum Depth of Binary Tree
UVA122 树的层次遍历 Trees on the level
UVA122 树的层次遍历 Trees on the level
【1094】The Largest Generation (树DFS-水题)
基础题。 这类题也是直接DFS,不是像上次的【1079】&【1090】供应树DFS一样是到了叶子结点就进行“更新/结算”类型,这题直接利用DFS统计每层的结点个数即可。
82 0
【1115】Counting Nodes in a BST (30分)【BST建树 DFS】
【1115】Counting Nodes in a BST (30分)【BST建树 DFS】 【1115】Counting Nodes in a BST (30分)【BST建树 DFS】
90 0
【1004】Counting Leaves (30 分)
【1004】Counting Leaves (30 分) 【1004】Counting Leaves (30 分)
78 0