根据树的两种遍历序列求第三种遍历序列

只知道先序序列和后序序列是无法求出唯一的树,所以不做讨论。

注意内存的释放,这里还没做- -

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

struct node{
	char c;
	node *l, *r;
	node(){
		l = NULL, r = NULL;
	}
}root1,root2;

char first[100], mid[100], last[100];

void preSearch(node *root)//先序遍历树
{
	if(root != NULL){
		printf("%c", root->c);
		preSearch(root->l);
		preSearch(root->r);
	}
	return ;
}

void midSearch(node *root)//中序遍历树
{
	if(root != NULL){
		midSearch(root->l);
		printf("%c", root->c);
		midSearch(root->r);
	}
	return ;
}

void postSearch(node *root)//后序遍历树
{
	if(root != NULL){
		postSearch(root->l);
		postSearch(root->r);
		printf("%c", root->c);
	}
	return ;
}

void BuildTreeFromPreAndMid(node *root, int ll, int lr, int len, int &now)//根据中序和先序求树
{
	root->c =*(first + now);
	int pos = (int)(strchr(mid, *(first + now)) - mid);
	now++;
	if(now >= len)
		return ;
	if(pos - 1 >= ll){
		node *t = new node;
		root->l = t;
		BuildTreeFromPreAndMid(root->l, ll, pos - 1, len, now);
	}
	if(pos + 1 <= lr){
		node *t = new node;
		root->r = t;
		BuildTreeFromPreAndMid(root->r, pos + 1, lr, len, now);
	}
}

void BuildTreeFromPostAndMid(node *root, int ll, int lr, int len, int &now)//根据中序和后序求树
{
	root->c =*(last + now);
	int pos = (int)(strchr(mid, *(last + now)) - mid);
	now--;
	if(now < 0)
		return ;
	if(pos + 1 <= lr){
		node *t = new node;
		root->r = t;
		BuildTreeFromPostAndMid(root->r, pos + 1, lr, len, now);
	}
	if(pos - 1 >= ll){
		node *t = new node;
		root->l = t;
		BuildTreeFromPostAndMid(root->l, ll, pos - 1, len, now);
	}
}

int main()
{
	gets(first);
	gets(mid);
	gets(last);
	int now = 0;
	BuildTreeFromPreAndMid(&root1, 0, strlen(first) - 1, strlen(first), now);

	int now2 = strlen(last);
	BuildTreeFromPostAndMid(&root2, 0, strlen(last) - 1, strlen(last), now2);

	postSearch(&root1);
	preSearch(&root2);
	return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值