版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
Problem Description
已知一个按先序输入的字符序列,如abd,eg,cf,(其中,表示空结点)。请建立该二叉树并按从上到下从左到右的顺序输出该二叉树的所有叶子结点。
Input
输入数据有多行,每一行是一个长度小于50个字符的字符串。
Output
按从上到下从左到右的顺序输出二叉树的叶子结点。
Sample Input
abd,eg,cf,
xnl,i,u,
Sample Output
dfg
uli
Hint
Source
xam
思路:
在层序遍历的基础上,判断该结点是不是叶子就可以了
#include <stdio.h>
#include <string.h>
#define MaxTree 10
int i;
typedef struct Node
{
char data;
struct Node* lchild;
struct Node* rchild;
} TreeNode;
TreeNode* create_tree(TreeNode* t, char str[])
{
char ch = str[i++];
if (ch == ',')
{
return NULL;
}
else
{
t = (TreeNode*)malloc(sizeof(TreeNode));
t->data = ch;
t->lchild = create_tree(t->lchild, str);
t->rchild = create_tree(t->rchild, str);
}
return t;
}
void Travel(TreeNode* t)
{
TreeNode *temp[55];
int front = 0, rear = 0;
temp[rear++] = t;
while(rear > front)
{
if (temp[front])
{
if (temp[front]->lchild == NULL&&temp[front]->rchild == NULL)
{
printf("%c", temp[front]->data);
}
temp[rear++] = temp[front]->lchild;
temp[rear++] = temp[front]->rchild;
}
front++;
}
}
int main()
{
TreeNode* root;
char str[55];
while(gets(str))
{
i = 0;
root = create_tree(root, str);
Travel(root);
printf("\n");
}
return 0;
}