RQNOJ21--FBI树(树形结构)

题目描述

  我们可以把由“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;

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值