中国大学MOOC-陈越、何钦铭-数据结构-2018秋 03-树2 List Leaves (25 分)

Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a "-" will be put at the position. Any pair of children are separated by a space.

Output Specification:

For each test case, print in one line all the leaves' indices in the order of top down, and left to right. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.

Sample Input:

8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6

Sample Output:

4 1 5

代码如下:

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
const int maxn=15;
int n,num;
int is[maxn];
struct tree
{
    int data;
    int left;
    int right;
};
tree t[maxn];
queue<tree>q;
void init()
{
    memset (is,0,sizeof(is));
    num=0;
}
void Ltraverse ()
{
    int root;
    for (int i=0;i<n;i++)
        if(!is[i])
       {
          root=i;
          break;
       }
    q.push(t[root]);
    while (!q.empty())
    {
        int Size=q.size();
        while (Size--)
        {
            tree temp=q.front();
            q.pop();
            if(temp.left==-1&&temp.right==-1)
            {
                if(num>1)
                    printf("%d ",temp.data);
                else
                    printf("%d\n",temp.data);
                num--;
            }
            if(temp.left!=-1)
                  q.push(t[temp.left]);
            if(temp.right!=-1)
                  q.push(t[temp.right]);
        }
    }
}
int main()
{
    scanf("%d\n",&n);
    init();
    for (int i=0;i<n;i++)
    {
        char l,r;
        int ci=0;
        t[i].data=i;
        scanf("%c %c",&l,&r);
        getchar();
        if(l!='-')
        {
           int lnum=l-'0';
           is[lnum]=1;
           t[i].left=lnum;
        }
        else
        {
            ci++;
            t[i].left=-1;
        }
        if(r!='-')
        {
            int rnum=r-'0';
            is[rnum]=1;
            t[i].right=rnum;
        }
        else
        {
            ci++;
            t[i].right=-1;
        }
        if(ci==2)
            num++;
    }
    Ltraverse();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41410799/article/details/82721714