1 #include<stdio.h> 2 #include<math.h> 3 #define MAX 10000 4 int num[MAX]; 5 char s[MAX]; 6 //定義結構體 7 struct Node{ 8 Node *left,*right; 9 char c; 10 }; 11 //將字符數組轉爲整形數組 12 void strtoint(char *s, int *num, int len) { 13 for(int i=0;i<len;i++){ 14 num[i] = s[i] - '0'; 15 } 16 } 17 //後序遍歷:遞歸遍歷左右子樹 18 void lastdfs(Node *head){ 19 if(head->left) 20 lastdfs(head->left); 21 if(head->right) 22 lastdfs(head->right); 23 printf("%c",head->c); 24 } 25 //判斷並返回01串是否爲全0、全一、混合串 26 char fbi(int *num,int begin,int end){ 27 int sum=0; 28 for(int i=begin;i<=end;i++) { 29 sum+=num[i]; 30 } 31 if(sum==0) return 'B';//全0串 32 else if(sum==end-begin+1) return 'I';//全1串 33 else return 'F';//混合串 34 } 35 //建立二叉樹 36 Node *buildTree(int *num, int begin, int end){ 37 char c = fbi(num,begin,end); 38 Node *p = new Node; 39 p->c = c; 40 if(begin<end){//說明子串不爲空 41 int mid = (begin+end)/2; 42 p->left = buildTree(num,begin,mid); 43 p->right = buildTree(num,mid+1,end); 44 }else{//若子串爲空,左右子樹賦NULL 45 p->left=NULL; 46 p->right=NULL; 47 } 48 return p; 49 } 50 int main(){ 51 int n; 52 scanf("%d",&n); 53 getchar();//處理回車 54 gets(s); 55 int len = pow(2,n);//按題意"01"串的長度爲2的n次方 56 strtoint(s,num,len); 57 Node *head = buildTree(num,0,len-1); 58 lastdfs(head); 59 return 0; 60 }