您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之二叉树七:叶子问题

2017-12-14 20:55 148 查看

Problem Description

已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立该二叉树并按从上到下从左到右的顺序输出该二叉树的所有叶子结点。

Input

 输入数据有多行,每一行是一个长度小于50个字符的字符串。

Output

 按从上到下从左到右的顺序输出二叉树的叶子结点。

Example Input

abd,,eg,,,cf,,,
xnl,,i,,u,,


Example Output

dfg
uli


用层序遍历的方法实现一层层的输出叶子数。

#include <bits/stdc++.h>

#include <string.h>

using namespace std;

int cnt, k, n;

char a[51], b[51];

struct node

{

    char data;

    struct node *l, *r;

};

struct node *create()

{

    struct node *root;

    root=(struct node*)malloc(sizeof(struct node));

    if(a[++cnt]==',')

        root = NULL;

    else

    {

        if(a[cnt])

        {

            root->data = a[cnt];

            root->l = create();

            root->r = create();

        }

    }

    return root;

}

void shuchu(struct node *root)

{

    int in=0, out=0;

    struct node *a[100];

    a[in++] = root;

    while(in>out)

    {

        if(a[out])

        {

            if(!a[out]->l&&!a[out]->r)

                cout << a[out]->data;

            a[in++]=a[out]->l;

            a[in++]=a[out]->r;

        }

        out++;

    }

}

int main()

{

    while(~scanf("%s", a))

    {

        struct node *root;

        cnt = -1;

        root = create();

        shuchu(root);

        cout << endl;

    }

    return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: