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

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description

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

Input

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

Output

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

Sample Input

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

Sample Output

dfg
uli

题解:建立二叉树然后找叶子,注意叶子是从“上到下从左到右的顺序”输出,即层序遍历

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct tree
{
    char data;
    struct tree *l,*r;
}tree;

int i;
char s[55];

tree *newtree()
{
    tree *t;
    t = (tree*)malloc(sizeof(tree));
    t->l = t->r = NULL;
    return t;
}

tree *creat()/*根据所给先序遍历建立二叉树*/
{
    tree *t = newtree();
    if(s[i++]==',')
        return NULL;
    t->data = s[i-1];
    t->l = creat();
    t->r = creat();
    return t;
}

/*用数组模拟队列进行二叉树的层序遍历找叶子*/
void get_num(tree *t)
{
    tree *q[55],*t1;
    int front,base;
    front = base = 0;
    if(t)
    {
        q[base++] = t;
    }
    while(front!=base)
    {
        t1 = q[front++];
        if(t1->l==NULL&&t1->r==NULL)
        {
            printf("%c",t1->data);
            continue;
        }
        if(t1->l)
            q[base++] = t1->l;
        if(t1->r)
            q[base++] = t1->r;
    }
}

int main()
{
    tree *t;
    while(scanf("%s",s)!=EOF)
    {
        i = 0;
        t = newtree();
        t = creat();
        get_num(t);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/luoxiaoyi/p/9848522.html
今日推荐