HDU 1710 Binary Tree Traversals(前序中序后序遍历)

http://acm.hdu.edu.cn/showproblem.php?pid=1710

题意:已知前序和中序遍历求后序遍历

这道题目按照我一开始的方法我发现做不了。。。因为他肯定有数据是专门比如一直左子树的,我用数组像写线段树那样模拟二叉树是不可取的,毕竟2的10000次方,根本开不出来这样的数组。后来看了看,发现,啊啊啊啊啊???这根本不需要存在数组啊,直接输出就行啊,详情看代码。

代码如下:注释掉的部分就是我一开始打算先放进数组再取出来的做法,太蠢了。

#include<bits/stdc++.h>
using namespace std;
int front[1005], mid[1005], tree[100005], back[1005];
int cnt = 0, n;
void build(int x, int fs, int fe, int ms, int me)
{
//	cout << front[fs] << " " << fs <<" "<< fe <<" "<<  ms <<" "<< me << endl;
	if(fs > fe)
		return;
	
	int root = ms;
	while(mid[root] != front[fs])
		root++;
	if(root - ms >= 1)
		build(x * 2, fs + 1, fs + root - ms, ms, root - 1);
	if(ms + root - ms <= fe)
		build(x * 2 + 1, fs + root - ms + 1, fe , root + 1, me);
	printf("%d%c", front[fs], x == 1 ? '\n' : ' ');
}

void print(int x)
{
	if(tree[x * 2] != -1)
		print(x * 2);
	if(tree[x * 2 + 1] != -1)
		print(x * 2 + 1);
	back[cnt++] = tree[x];
}

int main()
{
	while(cin >> n)
	{
		memset(tree, -1, sizeof(tree));
		cnt = 0;
		for(int i = 0; i < n; i++)
			cin >> front[i];
		for(int i = 0; i < n; i++)
			cin >> mid[i];
		build(1, 0, n - 1, 0, n - 1);
//		print(1);
//		for(int i = 0; i < cnt; i++)
//			printf("%d%c", back[i], i == cnt - 1 ? '\n' : ' ');
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值