1138. Postorder Traversal 解析

刚开始看题,觉得怎么考这么简单的题。。

然后一看N 50000 就知道是个大坑了. 建树是不行的.时间会超,递归到第一个值就可以了

#include <iostream>
#include <cstring>
#include <climits>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <set>

#define MAX 50010

using namespace std;
int n;
int pre[MAX];
int in[MAX];
int post[MAX];
int pp = 0;

struct node{
	node * l,* r;
	int data;
	node(){l = r = NULL;};
};
typedef node * tree;
bool isFind = false;


tree buildTree(int pl,int ph, int il,int ih,tree t){
	if(!isFind && pl <= ph){
		t = new node;
		t->data = pre[pl];
		int pos = -1;
		for(int i = il ;i <= ih;i++){
			if(in[i] == pre[pl]){
				pos = i;
				break;
			}
		}

		if(pos == -1)
			return NULL;
		else{
			t->l = buildTree(pl+1,pl+pos-il,il,pos-1,t->l);
			t->r = buildTree(pl+pos-il+1,ph,pos+1,ih,t->r);
			post[pp++] = t->data;
			if(pp == 1)
				isFind = true;
		}
	}

	return t;
}



int main(){
	
	scanf("%d",&n);
	for(int i = 0 ;i < n ;i++){
		scanf("%d",&pre[i]);
	}

	for(int i = 0 ;i < n ;i++){
		scanf("%d",&in[i]);
	}

	tree t = NULL;
	t=buildTree(0,n-1,0,n-1,t);
//	postorder(t);

	cout << post[0] << endl;


	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值