7-4 List Leaves

7-4 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

AC代码如下:

#include <iostream>
#include <string>
#include <queue>
using namespace std;

struct Node
{
    int data;
    char left;
    char right;
}T[20];
int n = 0;
int root = -1;
void build()
{
    char cl, ch;
    cin >> n;
    int i, j, k;
    int book [n];

    for (i = 0; i < n; i++)
    {
        book[i] = 0;
    }

    for (j = 0; j < n; j++)
    {
        cin >> cl >> ch;
        T[j].data = j;
        if (cl == '-')
        {
            T[j].left = -1;
        }
        else
        {
            T[j].left = cl - '0';
            book[cl-'0'] = 1;
        }
        if (ch == '-')
        {
            T[j].right = -1;
        }
        else
        {
            T[j].right = ch - '0';
            book[ch-'0'] = 1;
        }
    }
    for (k = 0; k < n; k++)
    {
        if (book[k] != 1)
        {
            root = k;
            break;
        }
    }
}

void traversal()
{
    queue <int> q;
    q.push(T[root].data);
    int arr[20];
    int i = 0;
    while (!q.empty())
    {
        int item = q.front();
        arr[i] = item;
        q.pop();
        if (T[item].left != -1)
        {
            q.push(T[item].left);
        }
        if (T[item].right != -1)
        {
            q.push(T[item].right);
        }
        i++;
    }
    bool flag = false;
    for (int j = 0; j < i; j++)
    {
        if (T[arr[j]].left == -1 && T[arr[j]].right == -1)
        {
            if(flag)
                cout << " ";
            cout << T[arr[j]].data;
            flag = true;
        }
    }
}
int main()
{
    build();
    traversal();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/fdkNeverStopLearning/article/details/81706076