03-2. List Leaves (25)

3243 단어 list
03-2. List Leaves (25)
시간 제한
400 ms
메모리 제한
65536 kB
코드 길이 제한
8000 B
판정 절차
Standard
작자
CHEN, Yue
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
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
#define lson ((root<<1)+1)
#define rson ((root<<1)+2)
#define MID ((l+r)>>1)
typedef long long ll;
typedef pair P;
#define For(i,t,n) for(int i=(t);i<(n);i++)
const int maxn=201;
const int base=1000;
const int inf=9999999;
const double eps=1e-5;
int T[maxn];
int f[maxn];//뿌리를 찾는 데 사용되며, 나타나지 않는 것은 뿌리이다
int n;
int main()
{
    int m,i,j,k,t;
    cin>>n;
    memset(T,-1,sizeof(T));
    memset(f,0,sizeof(f));
    for(i=0;i    {
        int l,r;
        char s[3],u[3];
        scanf("%s%s",u,s);
        if(s[0]=='-')
            r=-1;
        else
            r=atoi(s);
        if(u[0]=='-')
           l=-1;
        else
             l=atoi(u);
        T[(i<<1)+1]=l;
        T[(i<<1)+2]=r;
        f[l]++;
        f[r]++;
    }
    for(i=0;i        if(f[i]==0)break;
    queue q;//나무의 층이 두루 다니다
    q.push(i);
    int first=1;
    while(!q.empty())
    {
        int root=q.front();
        q.pop();
        if(T[rson]==-1&&T[lson]==-1)
        {
            if(first)
            {
                first=0;
                printf("%d",root);
            }
            else
                printf("%d",root);
        }
        if(T[lson]!=-1)
            q.push(T[lson]);
        if(T[rson]!=-1)
            q.push(T[rson]);
    }
    printf("");
    return 0;
}

좋은 웹페이지 즐겨찾기