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

来源:互联网 发布:js文本框获得值 编辑:程序博客网 时间:2024/05/20 11:46

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

Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic

Problem Description

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

Input

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

Output

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

Example Input

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

Example Output

dfguli

Hint

 

Author

 xam
#include <iostream>using namespace std;char s[1001];int flag=0;struct tree{    char data;    tree*left;    tree*right;};tree*build(tree*root){    if(s[flag]==',')    {        flag++;        return NULL;    }    else    {        root=new tree;        root->data=s[flag++];        root->left=build(root->left);        root->right=build(root->right);    }    return root;}void ans(tree*root){    if(root==NULL)        return;    tree*link[666];    int i=0,j=0;    link[j++]=root;    while(i<j)    {        if(link[i])        {            if(link[i]->left==NULL&&link[i]->right==NULL)                cout<<link[i]->data;                if(link[i]->left)                    link[j++]=link[i]->left;                if(link[i]->right)                    link[j++]=link[i]->right;        }        i++;    }}int main(){    tree*root;    while(cin>>s)    {        flag=0;        root=build(root);        ans(root);        cout<<endl;    }    return 0;}
#include <iostream>#include <queue>using namespace std;char s[1001];int flag=0;struct tree{    char data;    tree*left;    tree*right;};tree*build(tree*root){    if(s[flag]==',')    {        flag++;        return NULL;    }    else    {        root=new tree;        root->data=s[flag++];        root->left=build(root->left);        root->right=build(root->right);    }    return root;}void ans(tree*root){    if(root==NULL)        return;    queue<tree*>Q;    tree*q;    Q.push(root);    while(!Q.empty())    {        q=Q.front();        Q.pop();        if(!q->left&&!q->right)        cout<<q->data;        if(q->left)            Q.push(q->left);        if(q->right)            Q.push(q->right);    }}int main(){    tree*root;    while(cin>>s)    {        flag=0;        root=build(root);        ans(root);        cout<<endl;    }    return 0;}



阅读全文
0 0
原创粉丝点击