您的位置:首页 > 理论基础 > 数据结构算法

POJ 2255 重构二叉树

2013-08-31 17:16 288 查看
#include<iostream>
#include<string>
#include<fstream>

using namespace std;

//#define DEBUG

static const int MAXNODES = 500;
struct node
{
char c;
node *lc;
node *rc;
};
static struct node nodes[MAXNODES];
static int p = 0;

struct node * create(string in, string pre)
{
struct node *root = NULL;
if (pre.length() > 0)
{
root = &nodes[p++];
root->c = pre[0];
int i = in.find(root->c);
root->lc = create(in.substr(0, i), pre.substr(1, i));
root->rc = create(in.substr(i + 1), pre.substr(i+1));
}
return root;
}
void postorder(struct node* root)
{
if (!root)
return;
postorder(root->lc);
postorder(root->rc);
cout << root->c ;
}

int main()
{
#ifdef DEBUG
fstream cin("G:\\book\\algorithms\\acm\\Debug\\dat.txt");
#endif

string pre, in;
while (cin >> pre >> in)
{
postorder(create(in, pre));
cout << "\n";
}
return 0;
}

采用递归的方法,节点预先分配,可能分配的过多了。

对string 的find()和substr()的掌握。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ POJ 数据结构