Problem Description
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立该二叉树并按从上到下从左到右的顺序输出该二叉树的所有叶子结点。
Input
输入数据有多行,每一行是一个长度小于50个字符的字符串。
Output
按从上到下从左到右的顺序输出二叉树的叶子结点。
Sample Input
abd,,eg,,,cf,,,
xnl,,i,,u,,
Sample Output
dfg
uli
Hint
Source
xam
题解:建立起二叉树,层次遍历中遇到叶子节点输出即可。
#include<bits/stdc++.h>
using namespace std;
struct node
{
node *l,*r;
char data;
};
char a[111];
int top;
node *creat()
{
top++;
node *root;
root=new node;
if(a[top]==',')
root=NULL;
else
{
root=new node;
root->data=a[top];
root->l=creat();
root->r=creat();
}
return root;
}
void layershow(node *root)
{
queue<node*>que;//注意这里是node*,坑死我了
if(root) //一定要特判,不然会RE
{
que.push(root);
}
while(que.size())
{
node *root=que.front(); //常用手段
if(root->l==NULL&&root->r==NULL)
cout<<root->data;
que.pop();
if(root->l) //依次找左右儿子输出即可
{
que.push(root->l);
}
if(root->r)
{
que.push(root->r);
}
}
}
int main()
{
while(cin>>a)
{
top=-1;
node *root;
root=creat();
layershow(root);
cout<<endl;
}
return 0;
}
/***************************************************
User name: ACM18171信科1801张林
Result: Accepted
Take time: 0ms
Take Memory: 208KB
Submit time: 2019-02-25 13:20:14
****************************************************/