03-树2 List Leaves

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 N1. 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 <iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<cstring>
#define mod 1000000007
typedef long long ll;
using namespace std;
struct node
{
    int liftchild;
    int rightchild;
};
node a[20], b[20];
bool vis[20];
int ft(int t)
{
    for(int i = 0;i <t;i++)
    {
        if(!vis[i]&&(a[i].liftchild!=-1||a[i].rightchild!=-1))
        {
            return i;
        }
    }
}
int main()
{
    int t;
    scanf("%d", &t);
    getchar();
    for(int i = 0; i<t; i++)
    {
        char temp1, temp2;
        scanf("%c %c", &temp1, &temp2);
        getchar();
        if(temp1!='-')
        {
            a[i].liftchild = temp1-'0';
            vis[temp1-'0'] = 1;
        }
        else
            a[i].liftchild = -1;
        if(temp2!='-')
        {
            a[i].rightchild = temp2-'0';
            vis[temp2-'0'] = 1;
        }
        else
            a[i].rightchild = -1;
    }
    int root = ft(t);
    queue<int> que;
    que.push(root);
    int flag = 1;
    while(!que.empty())
    {
        int n = que.front();
        que.pop();
        if (a[n].liftchild == -1&& a[n].rightchild==-1)
        {
            if(flag)
            {
                printf("%d", n);
                flag = 0;
            }
            else
            {
                printf(" %d", n);
            }
        }
        else
        {
            if(a[n].liftchild!=-1)
                que.push(a[n].liftchild);
            if(a[n].rightchild!=-1)
                que.push(a[n].rightchild);
        }
    }
    return 0;
}

posted @ 2018-05-01 21:54  focus5679  阅读(118)  评论(0编辑  收藏  举报