88 FBI树

88 FBI树

作者: Turbo时间限制: 1S章节: 深度优先搜索

问题描述 :

  我们可以把由“0”和“1”组成的字符串分为三类:全“0”串称为B串,全“1”串称为I串,既含“0”又含“1”的串则称为F串。
  FBI树是一种二叉树,它的结点类型也包括F结点,B结点和I结点三种。由一个长度为2N的“01”串S可以构造出一棵FBI树T,递归的构造方法如下:
  1)T的根结点对应的内容为S,因此其类型与串S的类型相同;
  2)若串S的长度大于1,将串S从中间分开,分为等长的左右子串S1和S2;由左子串S1构造左子树T1,由右子串S2构造右子树T2。
  现在给定一个长度为2N的“01”串,请用上述构造方法构造出一棵FBI树,并输出它的后序遍历序列。

输入说明 :

第一行是一个整数N(0 <= N <= 10),第二行是一个长度为2N的“01”串。

输出说明 :

包括一行,这一行只包含一个字符串,即FBI树的后序遍历序列。

输入范例 :
3
10001011
输出范例 :
IBFBBBFIBFIIIFF

#include <iostream>
#include <stack>
#include <string>
#include <cstdio>
#include <cstring>
using namespace std;
stack<string> st;
string str1 = "F", str2 = "B", str3 = "I";//F=01 B=0 I=1
void FBI(string tree)
{
	int p[2] = { 0 };
	for (int i = 0; i<(int)tree.size(); i++)
	{
		p[tree[i] - '0']++;
	}
	if (p[0]>0 && p[1] > 0)
		st.push(str1);
	else if (p[0] > 0 && p[1] == 0)
		st.push(str2);
	else if (p[0] == 0 && p[1] > 0)
		st.push(str3);
}
void postOrder(string tree)
{
	if ((int)tree.size() > 0)
	{
		FBI(tree);
		int len = (int)tree.size() / 2;
		postOrder(tree.substr(len,len));
		postOrder(tree.substr(0, len));
	}
}
int main()
{
	int n;
	cin >> n;
	getchar();
	string tree;
	cin >> tree;
	postOrder(tree);
	while (!st.empty())
	{
		cout << st.top();
		st.pop();
	}
	return 0;
}
posted @ 2020-05-12 20:22  RabbitJwr  阅读(160)  评论(0编辑  收藏  举报