关闭

03-树2 List Leaves

标签: 数据结构
163人阅读 评论(0) 收藏 举报
分类:

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;
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:9799次
    • 积分:354
    • 等级:
    • 排名:千里之外
    • 原创:26篇
    • 转载:0篇
    • 译文:0篇
    • 评论:2条
    文章分类
    最新评论