鏈接:http://acm.sdibt.edu.cn/JudgeOnline/problem.php?id=2746
Description
用二叉樹的帶虛結點表示的前序遍歷序可以唯一的確定一棵二叉樹。
Input
輸入包含多組數據。
每行是一棵二叉樹的帶虛結點(#)表示的前序遍歷序串,長度不超過2000。每個結點為一個字符。
Output
對每行輸入,輸出對應二叉樹的中序遍歷序(不含虛結點)、后序遍歷序(不含虛結點)和層次遍歷序(不含虛結點)。
每棵二叉樹的輸出占一行,中序遍歷序、后序遍歷序和層次遍歷序之間用一個空格隔開。
Sample Input
ab##c##
#
ab###
Sample Output
bac bca abc
ba ba ab
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<string.h> 4 #include<queue> 5 #include <iostream> 6 using namespace std; 7 typedef struct node 8 { 9 char data; 10 struct node*lchild,*rchild; 11 } pjq; 12 char ch; 13 void creat(pjq **p,int a)//先序建樹 14 { 15 *p=NULL; 16 if(a) 17 ch=getchar(); 18 else 19 a=1; 20 if(ch=='\n') 21 return; 22 else 23 { 24 if(ch=='#') 25 *p=NULL; 26 else 27 { 28 *p=(pjq *)malloc(sizeof(pjq)); 29 (*p)->data=ch; 30 creat(&((*p)->lchild),a); 31 creat(&((*p)->rchild),a); 32 } 33 } 34 } 35 void print1(pjq *p)//中序輸出樹 36 { 37 if(p!=NULL) 38 { 39 print1(p->lchild); 40 printf("%c",p->data); 41 print1(p->rchild); 42 } 43 } 44 void print2(pjq *p)//后序輸出樹 45 { 46 if(p!=NULL) 47 { 48 print2(p->lchild); 49 print2(p->rchild); 50 printf("%c",p->data); 51 } 52 } 53 void print3(pjq *b)//層次遍歷輸出樹 54 { 55 if(b==NULL) 56 return ; 57 pjq *p; 58 pjq *q[2050]; 59 int front,last; 60 front=last=-1; 61 last++; 62 q[last]=b; 63 while(front!=last) 64 { 65 front=(front+1); 66 p=q[front]; 67 printf("%c",p->data); 68 if(p->lchild!=NULL) 69 { 70 last++; 71 q[last]=p->lchild; 72 } 73 if(p->rchild!=NULL) 74 { 75 last++; 76 q[last]=p->rchild; 77 } 78 } 79 } 80 int main() 81 { 82 pjq *p=NULL; 83 while((ch=getchar())!=EOF) 84 { 85 if(ch=='#') 86 printf("\n"); 87 else 88 { 89 int a=0; 90 creat(&p,a); 91 print1(p); 92 printf(" "); 93 print2(p); 94 printf(" "); 95 print3(p); 96 printf("\n"); 97 } 98 getchar(); 99 } 100 return 0; 101 }