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 (≤) 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<queue>
#define maxtree 11
using namespace std;

struct treenode//使用静态链表存储
{
    int data;
    int left;
    int right;
}T[maxtree];

int build_treee(treenode T[])//构建数的函数
{
    int root = -1;
    int n;//树的节点数
    cin>>n;
    bool check[n]={0};//hash表,判断某个结点是否被某个指针(子树)指向,是的话标记为1,也就是结点的左右指针的值对应check[]的下标
    char cl,cr;
    if(n)
    {
    for(int i=0;i<n;i++)
    {
        T[i].data = i;
        cin>>cl>>cr;//左右子树的地址先以char型表示,用以判断“-”

        if(cl=='-')
        {
            T[i].left = -1;
        }else
        {
            T[i].left = cl-'0';
            check[T[i].left] = true;
        }

        if(cr=='-')
        {
            T[i].right = -1;
        }else{

            T[i].right = cr - '0';
            check[T[i].right] = true;
        }

    }

    for(int i=0;i<n;i++)//寻找根节点,也就是没有任何一个结点指向的结点就是根节点
    {
        if(!check[i])
        {
            root = i;
            break;
        }
    }
    }
    return root;//返回根节点
}

int main()
{
    queue<int> q;//构建队列
    int res[maxtree];//保存要输出的结点的值,也就是叶节点的值

    int r;
    r = build_treee(T);
    if(r==-1)
        return 0;
    q.push(r);
    int i=0;
    while(!q.empty())//程序遍历
    {
        int temp = q.front();//出队
        q.pop();
        if((T[temp].left==-1)&&(T[temp].right==-1))
            res[i++] = T[temp].data;
        if(T[temp].left != -1)
            q.push(T[temp].left);
        if(T[temp].right != -1)
            q.push(T[temp].right);
    }

    for(int j=0;j<i-1;j++)
        cout<<res[j]<<" ";
    cout<<res[i-1]<<endl;


    return 0;
}

 

posted @ 2020-05-08 22:31  清明道人  阅读(165)  评论(0编辑  收藏  举报