1004. Counting Leaves (30) 树的遍历 DFS BFS

来源:互联网 发布:淘宝异想星球是什么 编辑:程序博客网 时间:2024/05/18 01:42

递归自己掌握的并不熟练,所以要多做一些树的题目了,来看一下今天的题目吧!

A family hierarchy is usually presented by a pedigree tree. Your job is to count those family members who have no child.
Input

Each input file contains one test case. Each case starts with a line containing 0 < N < 100, the number of nodes in a tree, and M (< N), the number of non-leaf nodes. Then M lines follow, each in the format:

ID K ID[1] ID[2] … ID[K]
where ID is a two-digit number representing a given non-leaf node, K is the number of its children, followed by a sequence of two-digit ID’s of its children. For the sake of simplicity, let us fix the root ID to be 01.
Output

For each test case, you are supposed to count those family members who have no child for every seniority level starting from the root. The numbers must be printed in a line, separated by a space, and there must be no extra space at the end of each line.

The sample case represents a tree with only 2 nodes, where 01 is the root and 02 is its only child. Hence on the root 01 level, there is 0 leaf node; and on the next level, there is 1 leaf node. Then we should output “0 1” in a line.

Sample Input
2 1
01 1 02
Sample Output
0 1

这是一道树的层序遍历问题,因为不确定每个节点有几个child,所以可以尝试采取左儿子右兄弟的结构。或者像这篇博文一样采用vector去存每个node的childs,采用递归的结构去计算每个depth的numOfNonLeaves。

我的实现代码:

#include<iostream>#include<vector>#include<map>using namespace std;const int MAX_SIZE = 101;typedef struct node{    int id;    int child_num;    vector<int> child;}Node;void countLeaves(Node* Tree, Node node, map<int, int>& res, int depth);int main(void){    int N, M;    Node tree[MAX_SIZE];    map<int, int> result;    cin >> N >> M;    for (int i = 0; i < N+1; ++i)    {        tree[i].id = 0;        tree[i].child_num = 0;    }    while (M--)    {        int ID, K ,child_input;        cin >> ID >> K;        tree[ID].child_num = K;        while (K--)        {            cin >> child_input;            tree[ID].child.push_back(child_input);        }    }    countLeaves(tree, tree[1], result, 1);    bool first = true;    for (map<int, int>::iterator iter = result.begin(); iter != result.end(); ++iter){        if (first)        {            cout << iter->second;            first = false;        }        else            cout << " " << iter->second;    }    system("pause");    return 0;}void countLeaves(Node* Tree, Node node, map<int, int>& res, int depth){    if (res[depth] == NULL)        res[depth] = 0;    if (node.child_num == 0)    {        ++res[depth];        return;    }           vector<int> childs = node.child;    for (size_t i = 0; i < childs.size(); ++i){        countLeaves(Tree, Tree[childs[i]], res, depth + 1);    }   }

points:初始化;size_t是一种“整型”类型,比如sizeof的结果就是size_t类型;递归说白了就是对于相同结构做相同的事,在实现的时候要注意他的出口和递归方向。

对于这样的dfs结构应当提笔就可以写出来,用二维数组保存每一个有孩子的结点以及他们的孩子结点,从根结点开始遍历,直到遇到叶子结点,就将当前层数depth的book[depth]++;标记第depth层拥有的叶子结点数,最后输出
void dfs(int index, int depth) {
if(v[index].size() == 0) {
book[depth]++;
maxdepth = max(maxdepth, depth);
return ;
}
for(int i = 0; i < v[index].size(); i++)
dfs(v[index][i], depth + 1);
}

如果用bfs,设立两个数组,第一个level,保存i结点的层数,为了bfs的时候可以让当前结点的层数是它的父结点层数+1,第二个数组book,保存i层所拥有的叶子结点的个数。变量maxlevel保存最大的层数

#include <cstdio>#include <queue>#include <vector>#include <algorithm>using namespace std;int level[100], book[100], maxlevel = -1;vector<int> v[100];void bfs() {    queue<int> q;    q.push(1);    level[1] = 0;    while(!q.empty()) {        int index = q.front();        q.pop();        maxlevel = max(level[index], maxlevel);        if(v[index].size() == 0)            book[level[index]]++;        for(int i = 0; i < v[index].size(); i++) {            q.push(v[index][i]);            level[v[index][i]] = level[index] + 1;        }    }}int main() {    int n, m, k, node, c;    scanf("%d %d", &n, &m);    for(int i = 0; i < m; i++) {        scanf("%d %d",&node, &k);        for(int j = 0; j < k; j++) {            scanf("%d", &c);            v[node].push_back(c);        }    }    bfs();    printf("%d", book[0]);    for(int i = 1; i <= maxlevel; i++)        printf(" %d", book[i]);    return 0;}
0 0
原创粉丝点击