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

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

Time Limit: 1000 ms Memory Limit: 65536 KiB

Submit Statistic

Problem Description

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

Input

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

Output

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

Sample Input

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

Sample Output

dfg
uli

Hint

 

Source

xam


#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char pre[55];
int l;

typedef struct node
{
    char data;
    struct node *left;
    struct node *right;
}tree;

tree *creat()
{
    tree *root;
    char p;
    p=pre[l++];
    if(p==',')
        return NULL;
    else
    {
        root=(tree *)malloc(sizeof(tree));
        root->data=p;
        root->left=creat();
        root->right=creat();
    }
    return root;
};//建树

void post(tree *root)
{
    int front=0,rear=0;
    tree *p[101];
    p[rear++]=root;
    while(rear>front)
    {
        if(p[front]!=NULL)
        {
            if(p[front]->left==NULL&&p[front]->right==NULL)
                printf("%c",p[front]->data);
            p[rear++]=p[front]->left;
            p[rear++]=p[front]->right;
        }
        front++;
    }
}



int main()
{
    int n;
    while(~scanf("%s",pre))
    {
        l=0;
        tree *root;
        root = (tree *)malloc(sizeof(tree));
        root=creat();
        post(root);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/rangran/article/details/81701037