题目描述
我们可以把由“0”和“1”组成的字符串分为三类:全“0”串称为B串,全“1”串称为I串,既含“0”又含“1”的串则称为F串。
FBI树是一种二叉树1,它的结点类型也包括F结点,B结点和I结点三种。由一个长度为2^N的“01”串S可以构造出一棵FBI树T,递归的构造方法如下:
1) T的根结点为R,其类型与串S的类型相同;
2) 若串S的长度大于1,将串S从中间分开,分为等长的左右子串S1和S2;由左子串S1构造R的左子树T1,由右子串S2构造R的右子树T2。
现在给定一个长度为2^N的“01”串,请用上述构造方法构造出一棵FBI树,并输出它的后序遍历2序列。
输入格式
输入的第一行是一个整数N(0<=N<=10),第二行是一个长度为2^N的“01”串。
输出格式
输出包括一行,这一行只包含一个字符串,即FBI树的后序遍历序列。
样例输入 样例输出
3 IBFBBBFIBFIIIFF
10001011
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <string>
using namespace std;
int N;
typedef struct BiTNode
{
char data;
struct BiTNode *left;
struct BiTNode *right;
}BiTNode,*BiTree;
int judge(string a)
{
int sum = 0;
for (int i = 0; i < a.size(); i++)
{
if (a[i]=='1')
sum++;
//if(sum!=a.size()&&sum!=0) return 2;
}
if (sum==0) return 0;
if (sum==a.size()) return 1;
return 2;
}
void createTree(BiTree &t,string b)
{
t = (BiTree)malloc(sizeof(BiTNode));
if(judge(b)==1) t->data = 'I';
if(judge(b)==2) t->data = 'F';
if(judge(b)==0) t->data = 'B';
t->left = NULL;
t->right = NULL;
if(b.size() == 1) return;
int num = b.size()/2;
string sleft = b.substr(0,num);
string sright = b.substr(num,b.size());
createTree(t->left,sleft);
createTree(t->right,sright);
}
void post(BiTree t)
{
if (t != NULL)
{
post(t->left);
post(t->right);
printf("%c",t->data);
}
}
BiTree root;
int main()
{
scanf("%d",&N);
string s;
cin >> s;
createTree(root,s);
post(root);
return 0;
}