数据结构实验之二叉树七:叶子问题
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;
}

本文介绍了一种算法,用于根据先序遍历的字符序列构建二叉树,并按从上到下、从左到右的顺序输出所有叶子节点。通过使用队列和递归创建二叉树结构,然后遍历树来找到并输出叶子节点。
2163

被折叠的 条评论
为什么被折叠?



