【二叉樹】SDUT 3341 遍歷二叉樹
阿新 • • 發佈:2018-11-26
Problem Description
已知二叉樹的一個按先序遍歷輸入的字元序列,如abc,,de,g,,f,,, (其中,表示空結點)。請建立二叉樹並按中序和後序的方式遍歷該二叉樹。
Input
連續輸入多組資料,每組資料輸入一個長度小於50個字元的字串。
Output
每組輸入資料對應輸出2行:
第1行輸出中序遍歷序列;
第2行輸出後序遍歷序列。
Sample Input
abc,,de,g,,f,,,
Sample Output
cbegdfa
cgefdba
#include <stdio.h> #include <stdlib.h> typedef struct no { char data; struct no *lc,*rc; }node; int l; node *creat(char a[]) { char c; node *root; if(!a[l]) return NULL; root=(node*)malloc(sizeof(node)); c=a[l++]; if(c==',')return NULL; root->data=c; root->lc=creat(a); root->rc=creat(a); return root; } void mid(node *root) { if(root) { mid(root->lc); printf("%c",root->data); mid(root->rc); } } void after(node *root) { if(root) { after(root->lc); after(root->rc); printf("%c",root->data); } } int main() { char a[60]; node *root; while(~scanf("%s",a)) { l=0; root=creat(a); mid(root); printf("\n"); after(root); printf("\n"); } return 0; }