数据结构实验之二叉树七:叶子问题

来源:互联网 发布:数据预处理常用函数 编辑:程序博客网 时间:2024/05/29 07:49

数据结构实验之二叉树七:叶子问题

Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic

Problem Description

已知一个按先序输入的字符序列,如abd,,eg,,,cf,,,(其中,表示空结点)。请建立该二叉树并按从上到下从左到右的顺序输出该二叉树的所有叶子结点。

Input

 输入数据有多行,每一行是一个长度小于50个字符的字符串。

Output

 按从上到下从左到右的顺序输出二叉树的叶子结点。

Example Input

abd,,eg,,,cf,,,xnl,,i,,u,,

Example Output

dfguli
题目中说要求输出叶子,而且顺序是从上至下从左至右的顺序,这就和也就是相当于一侧输出每一层的叶子,也就是将层序改一下判断一下层序遍历输出的结点是不是叶子,如果是的话就输出,这样输出的顺序就是题目中要求的顺序。
#include <stdio.h>#include <string.h>#include <stdlib.h>typedef struct node{              char data;struct node *lchild, *rchild;}*bitTree;int cnt = 0;char str[100];void createTree(bitTree &root, char str[]){char ch = str[cnt++];if(ch == ',')root = NULL;else {root = new node;root->data = ch;createTree(root->lchild, str);createTree(root->rchild, str);}}void getleaf(bitTree &root) {  int in = 0, out = 0;  struct node *a[1050];  a[in ++] = root;  while(in > out)  {    if (a[out] != NULL)     {        if(a[out]->lchild == NULL&& a[out]->rchild == NULL)            printf("%c",a[out] -> data);        else{            a[in ++] = a[out] -> lchild;            a[in ++] = a[out] -> rchild;       }     }     out ++;  } }int main(){while(~scanf("%s", str)){cnt = 0;bitTree root;createTree(root, str);getleaf(root);printf("\n");}return 0;}