数据结构实验之二叉树七:叶子问题
Description
已知一个按先序输入的字符序列,如abd,eg,cf,(其中,表示空结点)。请建立该二叉树并按从上到下从左到右的顺序输出该二叉树的所有叶子结点。
Input
输入数据有多行,每一行是一个长度小于50个字符的字符串。
Output
按从上到下从左到右的顺序输出二叉树的叶子结点。
Sample
Input
abd,,eg,,,cf,,,
xnl,,i,,u,,
Output
dfg
uli
Hint
注意输出的先是从上到下,从左到右
直接来代码
我是通过层序遍历来输出叶子节点的。
#include<bits/stdc++.h>
using namespace std;
typedef struct node
{
char data;
struct node *left;
struct node *right;
}Node;
char a[100];
int i;
Node *create()
{
Node *tree;
if(a[i]==',')
{
i++;
tree=NULL;
}
else
{
tree=(Node *)malloc(sizeof(Node));
tree->data=a[i];
i++;
tree->left=create();
tree->right=create();
}
return tree;
}
void yezi(Node *tree)
{
queue<Node *>q;
if(tree==NULL)
{
return ;
}
Node *front;
q.push(tree);
while(!q.empty())
{
front=q.front();
q.pop();
if(front->left==NULL&&front->right==NULL)
{
printf("%c",front->data);
}
if(front->left)
{
q.push(front->left);
}
if(front->right)
{
q.push(front->right);
}
}
}
int main()
{
while(scanf("%s",a)!=EOF)
{
i=0;
Node *tree;
tree=create();
yezi(tree);
printf("\n");
}
}