POJ 2255 重构二叉树

本文介绍了一种使用递归方法构建二叉树并进行后序遍历的C++实现方式,通过预定义字符串来构造树结构,并利用string类的find()与substr()方法辅助实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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()的掌握。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值