UVa536_Tree Recovery

题目:点击打开链接

思路:根据先序遍历找到树根,再在中序遍历中找到树根,从而找到左右树结点中序遍历,然后递归构造左右子树。

#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<stack>
#include<vector>
#include<queue>
#include<cstring>
#include<sstream>
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;

string pre_order, in_order;        //先序遍历、中序遍历
int lch[60], rch[60];              //左子树、右子树

int build(int L1, int R1, int L2, int R2){   //L1—R1为先序遍历,L2-R2为中序遍历
	if (L1 > R1) return 0;					//空树
	int  root = pre_order[L1]-'A'+1;        //在先序遍历中找到树根
	int p = L2;
	while (in_order[p]-'A'+1 != root) p++;  //在中序遍历中找到树根
	int cnt = p - L2;
	lch[root] = build(L1 + 1, L1 + cnt, L2, L2 + cnt - 1);  //关键
	rch[root] = build(L1 + cnt + 1, R1, L2 + cnt + 1, R2);
	return root;
}

void bfs(int root){
	if (lch[root])	bfs(lch[root]);
	if (rch[root])	bfs(rch[root]);
	printf("%c", root+'A'-1);
}

int main(){
	//freopen("random_numbers.txt","r",stdin);
	while (cin >> pre_order >> in_order){
		int len = pre_order.length();
		build(0, len - 1, 0, len - 1);
		bfs(pre_order[0]-'A'+1);		
		printf("\n");
	}
	return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值