【题目描述】
我们可以把由“0”和“1”组成的字符串分为三类:全“0”串称为B串,全“1”串称为I串,既含“0”又含“1”的串则称为F串。
FBI树是一种二叉树,它的结点类型也包括F结点,B结点和I结点三种。由一个长度为2N的“01”串S可以构造出一棵FBI树T,递归的构造方法如下:
T的根结点为R,其类型与串S的类型相同;
若串S的长度大于1,将串S从中间分开,分为等长的左右子串S1和S2;由左子串S1构造R的左子树T1,由右子串S2构造R的右子树T2。
现在给定一个长度为2N的“01”串,请用上述构造方法构造出一棵FBI树,并输出它的后序遍历序列。
【输入】
第一行是一个整数N(0≤N≤10),第二行是一个长度为2N的“01”串。
【输出】
一行,这一行只包含一个字符串,即FBI树的后序遍历序列。
【输入样例】
3
10001011
【输出样例】
IBFBBBFIBFIIIFF
题目分析:
很简单的一个题,建树然后后序遍历就行。但我一开始却因为一个非常细小的错误卡了十分种。
代码:
#include<iostream>
#include<string>
#include<algorithm>
#include<iomanip>
using namespace std;
typedef struct node;
typedef node *tree;//tree是指向node的指针
int n,len;
string s;
struct node
{
char date;
tree lchild,rchild;
};
tree bt;
void build(tree &bt,int l,int r)//建树
{
int t1=0,t0=0;
for(int i=l;i<=r;i++)//判断属于那种类型的结点
{
if(s[i]=='0') t0=1;
else if(s[i]=='1') t1=1;
if(t0&&t1) break;
}
char a;
if(t0&&t1) a='F';
else if(t0) a='B';
else if(t1) a='I';
bt=new node;//申请空间
bt->date=a;//赋值
bt->lchild=NULL;//先赋值为空树
bt->rchild=NULL;
if(l!=r)
{
build(bt->lchild,l,(l+r)/2);//建立左子树
build(bt->rchild,(l+r)/2+1,r);//建立右子树
}
return;
}
void postorder(tree bt)//后序遍历
{
if(bt)
{
postorder(bt->lchild);
postorder(bt->rchild);
cout<<bt->date;
}
}
int main()
{
cin.tie(0);
std::ios::sync_with_stdio(0);
cin>>n;
cin>>s;
len=s.size();
build(bt,0,len-1);
postorder(bt);
return 0;
}
而我一开始写的建树的代码是这样的
bt=new node;//申请空间
bt->date=a;//赋值
bt->lchild=NULL;//先赋值为空树
bt->rchild=NULL;
if(l!=r)
{
build(bt->lchild,l,r/2);//建立左子树
build(bt->rchild,r/2+1,r);//建立右子树
}
左右端点值弄错了,我却一直在找是不是别的地方错了,嗨呀,好气啊。