Uva - 536 - Tree Recovery



把字母的ASCII码减去A的ASCII码,再加1的正整数当作结点编号,根据前序遍历和中序遍历建二叉树,然后打印后序遍历。

刚开始没有加1,怎么都少输出结果,最后发现A的编号是0,直接递归终止了,所以这里一定要注意。。。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cstring>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <stack>
#include <queue>
#include <bitset> 
#include <cassert> 
#include <cmath>

using namespace std;

const int maxv = 30;
// 因为各个结点的字母都不相同,所以把字母的ASCII码减去A的ASCII码,再加1作为编号
// 不能直接用ASCII码减去A的ASCII码作为编号是因为A的编号为0,对于访问会认为失败
int firstOrder[maxv], inOrder[maxv], postOrder[maxv], lch[maxv], rch[maxv];
int n;

// 给出先序L1..R1和前序L2..R2递归建成一颗二叉树,返回树根
int build(int L1, int R1, int L2, int R2)
{
	if (L1 > R1) { // 空树
		return 0;
	}
	int root = firstOrder[L2]; // 先序遍历的第一个结点就是根
	int p = L1;
	while (inOrder[p] != root) {
		p++;
	}
	int cnt = p - L1; // 左子树的结点个数
	lch[root] = build(L1, p - 1, L2 + 1, L2 + cnt);
	rch[root] = build(p + 1, R1, L2 + cnt + 1, R2);
	return root;
}

// 从树根开始递归打印后序遍历
void printPostOrder(int root)
{
	if (lch[root]) {
		printPostOrder(lch[root]);
	}
	if (rch[root]) {
		printPostOrder(rch[root]);
	}
	cout << (char)(root + 'A' - 1);
	
}

int main()
{
	string line;
	while (cin >> line) {
		for (int i = 0; i < line.length(); i++) {
			firstOrder[i] = line[i] - 'A' + 1; // 这里加1的用意要好好体会
		}
		cin >> line;
		for (int i = 0; i < line.length(); i++) {
			inOrder[i] = line[i] - 'A' + 1;
		}
		int root = build(0, line.length() - 1, 0, line.length() - 1);
		printPostOrder(root);
		cout << endl;
	}

	return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值