codevs 1013 求先序排列

题目:codevs 1013

思路:已知后序遍历和中序遍历,不难知道后序的最后一个即为二叉树的根节点,在中序中找到这个节点,就可以知道左右子树的长度,多次递归即可求解,这题其实可以不用先序遍历二叉树,因为后序反过来就是先序了,所以建树的同时输出即可~

ps:一开始弄错了substr()函数第二个参数的含义,其第二个参数为截取字符串的长度,我错解为结束截取的位置,导致各种bug,不过终于还是改好了;

#include<iostream>
#include<string>
//#include<queue>
using namespace std;
typedef struct node 
{
	char data;
	node *lch;
	node *rch;
}*tree,node;
void creat(tree &h,string &mi,string &pos)
{
	if(mi.empty())
	{
		h = NULL;
		return;
	 }
	int pos_len = pos.size();
	int mi_len = mi.size();
	int p = mi.find(pos[pos_len-1]);
	string mi_lch = mi.substr(0,p);
	string mi_rch = mi.substr(p+1,pos_len-p-1);
	string pos_lch = pos.substr(0,p); 
	string pos_rch = pos.substr(p,pos_len-p-1);
	h = new node;
	if(h !=NULL)
	{
		h->data = pos[pos_len-1]; 
		cout << h->data; 
		creat(h->lch,mi_lch,pos_lch);
		creat(h->rch,mi_rch,pos_rch);
	}
}
int main()
{
	string mid,post;
	cin >> mid;
	cin >> post;
	tree root;
	creat(root,mid,post);
	return 0;
 } 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值