数据结构实验之二叉树七:叶子问题
Time Limit: 1000MS Memory limit: 65536K
题目描述
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立该二叉树并按从上到下从左到右的顺序输出该二叉树的所有叶子结点。
输入
输入数据有多行,每一行是一个长度小于50个字符的字符串。
输出
按从上到下从左到右的顺序输出二叉树的叶子结点。
示例输入
abd,,eg,,,cf,,, xnl,,i,,u,,
示例输出
dfguli
#include<bits/stdc++.h> using namespace std; struct node { char data; struct node *l; struct node *r; }; int i; string s; struct node *creat() { struct node *root; if(s[i++]==',') root=NULL; else { root=new node; root->data=s[i-1]; root->l=creat(); root->r=creat(); } return root; }; void leaf(struct node *root) { if(!root) return ; struct node *q[500]; int h=0,t=0; q[t++]=root; while(h<t) { if(!q[h]->l&&!q[h]->r) cout<<q[h]->data; if(q[h]->l) q[t++]=q[h]->l; if(q[h]->r) q[t++]=q[h]->r; h++; } } int main() { while(cin>>s) { i=0; struct node *root; root=creat(); leaf(root); cout<<endl; } return 0; }