已知二叉树的一个按先序遍历输入的字符序列,如abc,,de,g,,f,,, (其中,表示空结点)。请建立二叉树并按中序和后序的方式遍历该二叉树。
连续输入多组数据,每组数据输入一个长度小于50个字符的字符串。
每组输入数据对应输出2行:第1行输出中序遍历序列;第2行输出后序遍历序列。
abc,,de,g,,f,,,Example Output
cbegdfacgefdba#include<stdio.h>#include<string.h>#include<stdlib.h>typedef struct node{ char data ; struct node * lc; struct node * rc;}bitree;int i;bitree * pre_create(char str[51]){ bitree * t; if(str[++i]!=',') { t=(bitree *)malloc(sizeof(bitree)); t->data=str[i]; t->lc=pre_create(str); t->rc=pre_create(str); } else { t=NULL; } return t;}void inshow(bitree * tree){ bitree * t; t=tree; if(t!=NULL) { inshow(t->lc); printf("%c",t->data); inshow(t->rc); }}void postshow(bitree * tree){ bitree * t; t=tree; if(t!=NULL) { postshow(t->lc); postshow(t->rc); printf("%c",t->data); }}int main(){ int len; char str[51]; bitree * tree; while(scanf("%s",str)!=EOF) { i=-1; len=strlen(str); tree=pre_create(str); inshow(tree); printf("/n"); postshow(tree); printf("/n"); } return 0;}
新闻热点
疑难解答