03-树2 List Leaves

来源:互联网 发布:java使用odata 编辑:程序博客网 时间:2024/05/29 18:33
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 integerNNN (≤10\le 1010) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 toN−1N-1N1. Then NNN 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:

81 -- -0 -2 7- -- -5 -4 6

Sample Output:

4 1 5
#include <iostream>#include<cstring>#include<queue>using namespace std;int N;class Tree{public :    int left;    int right;    int pos;    friend istream&operator>>(istream &in,Tree &t)    {        char a,b;        in>>a>>b;        if(a!='-')t.left=a-'0';        else t.left=-1;        if(b!='-')t.right=b-'0';        else t.right=-1;    }};bool isLeaf(Tree t1){    if(t1.left==-1&&t1.right==-1)        return true;    return false;}Tree qRoot(Tree *t){    int *check=new int [N];    memset(check,0,sizeof(int)*N);    for(int i=0; i<N; i++)    {        if(t[i].left!=-1)check[t[i].left]=1;        if(t[i].right!=-1)check[t[i].right]=1;    }    for(int i=0; i<N; i++)    {        if(!check[i])return t[i];    }}
int main(){    cin>>N;    Tree *t=new Tree[N];    for(int i=0; i<N; i++)    {        cin>>t[i];        t[i].pos=i;    }    Tree r=qRoot(t);    if(isLeaf(r))    {        cout<<r.pos<<endl;        return 0;    }    int *a=new int [N],i=0;    for(int j=0; j<N; j++)a[j]=-1;    queue<Tree>t1;//Queue    t1.push(r);    while(!t1.empty())    {        cout<<t1.front().pos;        if(isLeaf(t1.front()))        {            a[i++]=t1.front().pos;        }        if (t1.front().left!=-1)            t1.push(t[t1.front().left]);        if(t1.front().right!=-1)            t1.push(t[t1.front().right]);        t1.pop();    }    for(int j=0; j<i-1; j++)        cout<<a[j]<<" ";    cout<<a[i-1];
}