已知二叉樹的一個按先序遍歷輸入的字符序列,如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;}
新聞熱點
疑難解答