數據結構實驗之二叉樹二:遍歷二叉樹
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
已知二叉樹的一個按先序遍歷輸入的字符序列,如abc,,de,g,,f,,, (其中,表示空結點)。請建立二叉樹並按中序和后序的方式遍歷該二叉樹。
Input
連續輸入多組數據,每組數據輸入一個長度小於50個字符的字符串。
Output
每組輸入數據對應輸出2行:
第1行輸出中序遍歷序列;
第2行輸出后序遍歷序列。
Sample Input
abc,,de,g,,f,,,
Sample Output
cbegdfa
cgefdba
PS:如果對二叉樹的遍歷沒有了解的話請先看我的另一篇博客 二叉樹的四種遍歷方式
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct tree//樹的節點
{
char data;
struct tree *l,*r;
}tree;
int i;
char s[55];
tree *newtree()//開辟新節點
{
tree *t;
t = (tree*)malloc(sizeof(tree));
t->l = t->r = NULL;
return t;
}
tree *creat()//根據給出的字符串建樹
{
tree *t = newtree();
if(s[i++]==',')
return NULL;
t->data = s[i-1];
t->l = creat();
t->r = creat();
return t;
}
void show_mid(tree *t)//中序遍歷
{
if(t)
{
show_mid(t->l);
printf("%c",t->data);
show_mid(t->r);
}
}
void show_back(tree *t)//后序遍歷
{
if(t)
{
show_back(t->l);
show_back(t->r);
printf("%c",t->data);
}
}
int main()
{
tree *t;
while(scanf("%s",s)!=EOF)
{
i = 0;
t = newtree();
t = creat();
show_mid(t);
printf("\n");
show_back(t);
printf("\n");
}
return 0;
}