数据结构二叉树:叶子问题

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

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

Hint

   思路:

先建树后层次遍历   

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include<queue>
using namespace std;
typedef struct node
{
    char data;
    node *lchild;
    node *rchild;
}BiTode,*BiTree;
queue<BiTree> q;
int top=0;
BiTree creat(char *p)//建树方法
{
    BiTree root=NULL;
    if(top<strlen(p))
    {
        if(p[top]!=',')
        {
            root=(struct node*)malloc(sizeof(struct node));
            root->lchild=NULL;
            root->rchild=NULL;
            root->data=p[top++];
            root->lchild=creat(p);//直到遇到逗号,该结点处的左子树建立完毕,然后继续下面的右子树。
            root->rchild=creat(p);
        }
        else
        {
            top++;
        }
    }
    return root;
}
cengci(BiTree t,char last[]){
    int j=0;
    BiTree s;
    q.push(t);
    s=NULL;
    while(!q.empty()){
        s=q.front();
        if(s->lchild==NULL&&s->rchild==NULL){
            last[j++]=s->data;
        }
        q.pop();
        if(s->lchild!=NULL)
            q.push(s->lchild);
        if(s->rchild!=NULL)
            q.push(s->rchild);
    }
        return j;
}
int main()
{
    char p[60],last[60];
    while(scanf("%s", p)!=EOF)
    {
        BiTree root;
        top=0;
        root=creat(p);
        int count1=cengci(root,last);
        for(int k=0;k<count1;k++){
            printf("%c",last[k]);
        }
        printf("\n");
    }
}

猜你喜欢

转载自blog.csdn.net/lijunyan5/article/details/80462793