数据结构实验之二叉树二:遍历二叉树

来源:互联网 发布:淘宝食品类目有哪些 编辑:程序博客网 时间:2024/04/30 03:23

数据结构实验之二叉树二:遍历二叉树

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

Problem Description

已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并按中序和后序的方式遍历该二叉树。

Input

连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。

Output

每组输入数据对应输出2行:
第1行输出中序遍历序列;
第2行输出后序遍历序列。

 

Example Input

abc,,de,g,,f,,,

Example Output

cbegdfacgefdba

Hint

 

Author

 xam
01#include <stdio.h>
02#include <string.h>
03#include <stdlib.h>
04typedef struct node
05{
06    char data;
07    struct node *l,*r;
08}tree;
09char st[51];
10int i;
11tree *creat(tree *root)                                     //这里是以先序遍历完成的树的保存
12{
13 
14    if(st[++i]==',')
15    {
16        root=NULL;
17    }
18    else
19    {
20        root = (tree *)malloc(sizeof(tree));
21        root->data = st[i];
22        root->l = creat(root->l);
23        root->r = creat(root->r);
24    }
25    return root;
26}
27void zhongxu(tree *root)          //中序遍历
28{
29    if(root)
30    {
31        zhongxu(root->l);
32        printf("%c",root->data);
33        zhongxu(root->r);
34    }
35}
36void houxu(tree *root)               //后序遍历
37{
38    if(root)
39    {
40        houxu(root->l);
41        houxu(root->r);
42        printf("%c",root->data);
43    }
44}
45int main()
46{
47    while(~scanf("%s",st))
48    {
49        i = -1;
50        tree *root;
51        root = creat(root);
52        zhongxu(root);
53        printf("\n");
54        houxu(root);
55        printf("\n");
56    }
57    return 0;
58}


0 0
原创粉丝点击