数据结构实验之二叉树七:叶子问题
Time Limit: 1000MS
Memory Limit: 65536KB
Problem Description
已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立该二叉树并按从上到下从左到右的顺序输出该二叉树的所有叶子结点。
Input
输入数据有多行,每一行是一个长度小于
50
个字符的字符串。
Output
按从上到下从左到右的顺序输出二叉树的叶子结点。
Example Input
abd,,eg,,,cf,,, xnl,,i,,u,,
Example Output
dfg uli
这种顺序其实就是层次遍历的顺序呐。
这次的队列没有用STL的,提供一次普通的模版。
注意:
还是要注意一开始的头结点就是空的状态!!!
还有什么不会的直接留言即可。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN=50+5;
struct node
{
char key;
struct node *left,*right;
};
struct node*creat()
{
struct node *p=new node;
p->left=p->right=NULL;
return p;
};
int num,l;
char s[MAXN];
struct node *in_build_tree(struct node *root)
{
if(num>l)return 0;
if(s[num]==',')return 0;
root=creat();
root->key=s[num];
num++;
root->left=in_build_tree(root->left);
num++;
root->right=in_build_tree(root->right);
return root;
};
void get_leaves(struct node *root)
{
struct node *q[MAXN];
int head=0,tail=0;
if(root)q[tail++]=root;
while(head<tail)
{
struct node *k=q[head++];
if(!k->left&&!k->right)printf("%c",k->key);
else
{
if(k->left)q[tail++]=k->left;
if(k->right)q[tail++]=k->right;
}
}
}
int main()
{
while(~scanf("%s",s))
{
num=0;
l=strlen(s);
struct node *root=in_build_tree(root);
get_leaves(root);
puts("");
}
return 0;
}