A1086

本题的关键是对所给样例的理解,看了算法笔记才明白,push的次序是先序遍历顺序,pop的次序是中序遍历顺序.其余跟A1020一样.
A1020通过后序、中序遍历获取二叉树
A1086通过先序、中序遍历获取二叉树

#include<cstdio>
#include<cstdlib>
#include<string.h>
#include<math.h>
#include<iostream>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=35;
int flag,n,preorder[maxn],inorder[maxn],pre=1,in=1;
struct node{
	int data;
	node* lchild;
	node* rchild;
};
node* binary(int preL,int preR,int inL,int inR){
	if(preL>preR){
		return NULL;
	}
	node* root=new node;
	root->data=preorder[preL];
	int k=inL;
	while(inorder[k]!=preorder[preL]){
		k++;
	}
	int left_len=k-inL;
	int right_len=inR-k;
	root->lchild=binary(preL+1,preL+left_len,inL,k-1);
	root->rchild=binary(preR-right_len+1,preR,k+1,inR);
	return root;                                                      //忘了将根结点返回出去 
}
void dfs(node* root){
	if(root==NULL){
		return;
	}
	dfs(root->lchild);
	dfs(root->rchild);
	if(root->data==flag){
		printf("%d",root->data);
	}else{
		printf("%d ",root->data);
	}
}
int main(){
	#ifdef ONLINE_JUDGE
	#else
		freopen("1.txt","r",stdin);
	#endif
	char str[5];
	stack<int> s;
	scanf("%d",&n);
	for(int i=0;i<n*2;i++){
		scanf("%s",str);
		if(strcmp(str,"Push")==0){
			scanf("%d",&preorder[pre++]);
			s.push(preorder[pre-1]);
		}else{
			inorder[in++]=s.top();
			s.pop();
		}
	}
	node* root=binary(1,pre-1,1,in-1);
	flag=root->data;
	dfs(root);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值