UVa 536 Tree Recobery 二叉树重建

这个题看着比较简单就先做了,虽然用了不少时间,但是也学到了不少东西,对二叉树的遍历有了进一步的了解,然后就是提交答案的时候,有一些细节没有注意,提交了3次才过

思路:递归建立二叉树,用映射给节点编号,直到中序遍历建立二叉树结束为止,建立的同时输出后序遍历

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <map>
using  namespace std;
char x[1024],z[1024],ltr[1024],rtr[1024];
map<char,int> tree;
void tmap(char s[])
{
	for(int i=0;i<strlen(s);i++)
	{
		tree[s[i]] = i;
	}
}

char build(int D1,int D2,int L1,int L2)
{
	if(L1>L2) return '0';
	char root=x[D1];
	int p = L1;
	while(z[p]!=x[D1]) p++;
	int cnt = p-L1;
	int troot = tree[root];
	ltr[troot] = build(D1+1,D1+cnt,L1,p-1);
	rtr[troot] = build(D1+cnt+1,D2,p+1,L2);
	cout<<root;
	return root;
}

int main()
{
      while(cin>>x>>z)
      {
      	   tree.clear();
      	   memset(ltr,'0',sizeof(ltr));
      	   memset(rtr,'0',sizeof(rtr));
           tmap(x);
           int n = strlen(x);
           tree['0'] = -1;
           build(0,n-1,0,n-1);
           cout<<endl;
      }
      return 0;
}
 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值