这个题的是本质就是建树和遍历树,不过完全可以将建树和遍历树的过程合并在一起。
建树过程,就是将原字符串一分为二,左一半右一半。由于是后序遍历,所以是在两侧树都建完后在输出。这里要注意只有一个字符的特殊情况。
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
using namespace std;
char tree[1030];
int n;
char judge(int l, int r) {
char c = tree[l];
for (int i = l + 1; i <= r; i++) {
if (tree[i] != c)
return 'F';
}
if (c == '0')
return 'B';
else
return 'I';
}
void maketree(int l, int r) {
if (l > r)
return;
else if (l == r) {
char a[3] = "BI";
if (tree[l] == '0')
cout << a[0];
else
cout << a[1];
return;
}
int mid = (l + r) >> 1;
maketree(l, mid);
maketree(mid + 1, r);
cout << judge(l, r);
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
cin >> n;
for (int i = 0; i < pow(2, n); i++)
cin >> tree[i];
maketree(0, pow(2, n) - 1);
return 0;
}