1086 Tree Traversals Again (25 分)

1086 Tree Traversals Again (25 分)

题意

给出二叉树的前序和中序遍历序列,求后序遍历序列。

思路

方法同1020 Tree Traversals (25 分)
通过前序序列和中序序列构建二叉树。
前序序列第一个为根root,查找中序序列root的位置,可以得到左右子树结点的数量,递归建树。
输出后序序列,注意结尾没有空格。
后续遍历二叉树 :先左子树 再右子树,最后输出根节点。

代码

#include<stdio.h>
#include<iostream>
#include<stack>
#include<string>
#include<queue>
using namespace std;
typedef struct node{
	int data;
	node *lchild,*rchild;
}node;
stack<int>st;
queue<int>q;
int pre[40],post[40],in[40];
node* creat(int lpre,int rpre,int lin,int rin)
{
//	printf("@@@@@\n");
	int temp;
	if(lpre>rpre){
		return NULL;
	}
	node *root;
	root=new node;
	root->data=pre[lpre];
	for(int i=lin;i<=rin;i++){	//注意这里是小于等于
		if(in[i]==pre[lpre]){
			temp=i;
			break;
		}
	}
	int numl=temp-lin;
	root->lchild=creat(lpre+1,lpre+numl,lin,temp-1);
	root->rchild=creat(lpre+numl+1,rpre,temp+1,rin);
	return root;
}
void treepost(node* root)
{
	if(root!=NULL){
		treepost(root->lchild);
		treepost(root->rchild);
		q.push(root->data);
	}
}
int main()
{
	int n,pr=0,po=0,ins=0,y;
	node *root;
	char x[50];
	scanf("%d",&n);
	int m=n*2;
	while(!st.empty()){
		st.pop();
	}
	for(int i=0;i<m;i++){
		scanf("%s",x);
		if(x[1]=='o'){
			in[ins++]=st.top();
			st.pop();
		}else{
			scanf("%d",&y);
			pre[pr++]=y;
			st.push(y);
		}
	}
//	for(int i=0;i<n;i++){
//		printf("%d  %d\n",pre[i],in[i]);
//	}
//	printf("$$$\n");
	root=creat(0,n-1,0,n-1);
//	printf("###\n");
	treepost(root);
	printf("%d",q.front());
	q.pop();
	while(!q.empty()){
		printf(" %d",q.front());
		q.pop();
	}
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值