浙大数据结构03-树2 List Leaves

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 
#define x first
#define y second
using namespace std;
typedef long long ll;
typedef struct
{
    int left,right;
}node;
int buildTree(vector&tree)
{
    int n;
    cin>>n;
    int vis[16];
    for(int i=0;i>cl>>cr;
        if(cl != '-')
        {
            tree[i].left = cl-'0';
            vis[tree[i].left]=1;
        }
        else
        {
            tree[i].left = -1;
        }
        if(cr != '-')
        {
            tree[i].right = cr-'0';
            vis[tree[i].right]=1;
        }
        else
        {
            tree[i].right = -1;
        }
    }
    for(int i=0;itree(16);
    int root=buildTree(tree),flag=0;
    queueq;
    if(root != -1)
        q.push(root);
    while(!q.empty())
    {
        int top=q.front();
        q.pop();
        node t=tree[top];
        if(t.left != -1)
        {
            q.push(t.left);
        }
        if(t.right != -1)
        {
            q.push(t.right);
        }
        if(t.left == -1 && t.right == -1)
        {
            if(flag)
                cout<< " "<< top;
            else
            {
                flag=1;
                cout<< top;
            }
        }
    }
    return 0;
}

你可能感兴趣的:(浙大数据结构,数据结构,list,elasticsearch,1024程序员节)