数据结构实验之二叉树七:叶子问题
数据结构实验之二叉树七:叶子问题
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
Source
xam
#include <bits/stdc++.h>
using namespace std;
struct bitree
{
char data;
struct bitree *lc;
struct bitree *rc;
};
char str[51];
int i;
bitree *create()
{
bitree *tree;
if(str[++i]==',')
tree = NULL;
else
{
tree = new bitree;
tree->data = str[i];
tree->lc = create();
tree->rc = create();
}
return tree;
}
void leaf(bitree *tree)
{
queue<bitree*>s;
s.push(tree);
while(!s.empty())
{
tree = s.front();
s.pop();
if(tree)
{
if((!tree->lc)&&(!tree->rc))
cout<<tree->data;
s.push(tree->lc);
s.push(tree->rc);
}
}
}
int main()
{
bitree *tree;
while(cin>>str)
{
i = -1;
tree = create();
leaf(tree);
cout<<endl;
}
return 0;
}

浙公网安备 33010602011771号