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 NN (\le 10≤10) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N-1N−1. Then NN 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>
using namespace std;

//#define Elementtype int
#define null -1
typedef struct Bintree
{
    //Elementtype data;
    int left;
    int right;
}Bintree;
Bintree* bintree;
int treenum ;
int* flag;
void input()
{

    cin >> treenum;

    bintree = new Bintree[treenum];
    flag = new int[treenum];

    char temp = 0;
    for (int i = 0; i < treenum; i++)
    {
        cin >> temp;
        if (temp == '-')
        {
            bintree[i].left = -1;
        }
        else
        {
            bintree[i].left = temp - '0';
            flag[bintree[i].left] = 1;
        }

        cin >> temp;
        if (temp == '-')
        {
            bintree[i].right = -1;
        }
        else
        {
            bintree[i].right = temp - '0';
            flag[bintree[i].right] = 1;
        }

    }
    delete[]bintree;
    delete[]flag;
}

int findtop()
{
    for (int i = 0; i < treenum; i++)
    {

        if (flag[i] != 1)
            return i;
    }
}

void traverse()
{
    int top = findtop();

    queue<int> q;
    q.push(top);

    while (!q.empty())
    {
        top = q.front();
        q.pop();

        if (bintree[top].left != null)
        {
            q.push(bintree[top].left);
        }
        if (bintree[top].right != null)
        {
            q.push(bintree[top].right);
        }
        if (bintree[top].left == null&&bintree[top].right == null)
        {
            if (!q.empty())
                cout << top << ' ';
            else
                cout << top;
        }
    }


}

int main()
{
    input();
    traverse();


    return 0;
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25716575/article/details/51564743
文章标签: 数据结构
个人分类: 数据结构
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

03-树2 List Leaves

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭