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

来源:互联网 发布:章子怡长相知乎 编辑:程序博客网 时间:2024/05/29 08:28

Problem Description

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

Input

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

Output

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

Example Input

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

Example Output

dfguli

Hint

 

Author



层序遍历的基础上找叶子



#include <iostream>
#include <stdlib.h>
using namespace std;




typedef struct binode
{
    char data;
    struct binode *lchild;
    struct binode *rchild;
}binode, *bitree;
char a[55];
int i;
bitree creat(bitree &T)
{
    if(a[i++] == ',')
        T = NULL;
    else
    {
        T = new binode;
        T->data = a[i - 1];
        T->lchild = creat(T->lchild);
        T->rchild = creat(T->rchild);
    }
    return T;
}
void browse(bitree T)
{
    int i = 0;
    int j = 0;
    bitree a[55];
    a[i++] = T;
    while(i > j)
    {
        if(a[j])
        {
            if(!a[j]->lchild && !a[j]->rchild)
                cout<<a[j]->data;
            if(a[j]->lchild)
                a[i++] = a[j]->lchild;
            if(a[j]->rchild)
                a[i++] = a[j]->rchild;
        }
        j++;
    }
}
int main()
{
    while(cin>>a)
    {
        bitree T;
        i = 0;
        T = creat(T);
        browse(T);
        cout<<endl;
    }
    return 0;
}

阅读全文
0 0