二分木のI-データ構造実験No.7:葉の問題

説明

abd、たとえばcfなどの順序で入力された文字のシーケンスを知っている(ここで、は空のノードを表します)。二分木を構築し、二分木のすべてのリーフノードを上から下、左から右に出力してください。
入力

入力データには複数行があり、各行は50文字未満の文字列です。
出力

二分木のリーフノードを上から下、左から右に出力します。
サンプル

入力

abd、eg、cf、
xnl、i、u、
出力

DFG
ULI

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int k;
char a[100];
struct node
{
    
    
    char data;
    struct node * ltree,* rtree;
};
void cengci(struct node * root)
{
    
    
    if(root==NULL)
    {
    
    
        return ;
    }
    int f,r;
    f=1;r=1;
    struct node * s[100],*p;
    s[1]=root;
    while(f<=r)
    {
    
    
        p=s[f++];
        if(p->rtree==NULL&&p->ltree==NULL)
        {
    
    
            printf("%c",p->data);
        }
        if(p->ltree!=NULL)
        {
    
    
            s[++r]=p->ltree;
        }
        if(p->rtree!=NULL)
        {
    
    
            s[++r]=p->rtree;
        }
    }
}
struct node * create(struct node * root)
{
    
    
    root=(struct node *)malloc(sizeof(struct node));
    if(a[k]!=',')
    {
    
    
        root->data=a[k++];
        root->ltree=create(root->ltree);
        root->rtree=create(root->rtree);
    }
    else if(a[k]==',')
    {
    
    
        root=NULL;
        k++;
    }
    return root;
}
int main()
{
    
    
    struct node * root;
    while(gets(a))
    {
    
    
        k=0;;
        root=create(root);
        cengci(root);
        printf("\n");
    }
    return 0;
}

おすすめ

転載: blog.csdn.net/a675891/article/details/103964015