PAT-A 1086 Tree Traversals Again (25)(25 分)栈预处理+先中定序

https://pintia.cn/problem-sets/994805342720868352/problems/994805380754817024

1086 Tree Traversals Again (25)(25 分)

An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.

\ Figure 1

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (<=30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: "Push X" where X is the index of the node being pushed onto the stack; or "Pop" meaning to pop one node from the stack.

Output Specification:

For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.

Sample Input:

6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop

Sample Output:

3 4 2 6 5 1

思路及关键点:

Push的次序就是先根序列,Pop的次序就是中根序列。于是此题就转换成了先中定序的基础题目。

本题关键在于如何预处理数据得到pre数组和in数组。

//先中定序,输出后根序列 
//先根序列、中根序列需要预处理 
#include <iostream>
#include <cstdio>
#include <stack>
#include <cstring> 
using namespace std; 
const int nmax=40;
struct node{
	int data;
	node* lchild;
	node* rchild;
};
int pre[nmax],in[nmax];
int n;//节点总数 

node* Create(int preL,int preR,int inL,int inR){//后中定序 
	node* root=NULL;
	if(preL>preR){
		root=NULL;
		return root;
	} 
	else{
		root=new node;
		root->data=pre[preL];
		//root->lchild=NULL;
		//root->rchild=NULL;
		
		int k;
		for(k=inL;k<=inR;k++){//找到中根序列的分界点 
			if(in[k]==pre[preL]){
				break;
			}
		}
		int  numleft=k-inL;
		root->lchild=Create(preL+1,preL+numleft,inL,k-1);//创建左子树 
		root->rchild=Create(preL+numleft+1,preR,k+1,inR);//创建右子树 
		return root;
	}
}

int num=0;//已输出节点个数 
void PostOrder(node* root){
	if(root==NULL){
		return;
	}
	PostOrder(root->lchild);
	PostOrder(root->rchild);
	printf("%d",root->data);
	num++;
	if(num<n){
		printf(" ");
	} 
} 

int main(int argc, char** argv) {
	while(cin>>n){
		char s[5];
		stack<int> st;
		int x;//操作数
		int preIndex=0;
		int inIndex=0;
		for(int i=0;i<2*n;i++){
			scanf("%s",s);
			//如果是Push操作,预处理得到pre数组 
			if(strcmp(s,"Push")==0){
				scanf("%d",&x);//读入操作数
				pre[preIndex++]=x;
				st.push(x); 
			}
			//如果是Pop操作,预处理得到in数组 
			else{//Pop();
				in[inIndex++]=st.top();
				st.pop();
			}
		} 
		node* root=Create(0,n-1,0,n-1);
		PostOrder(root);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qian2213762498/article/details/81710872
今日推荐