PAT.A1086 Tree Traversals Again

Back to Contents

Insert picture description here

Title

The stack is used to simulate the pre-order sequence and mid-order sequence of a binary tree, and the post-order traversal sequence of the binary tree is obtained.

Sample (can be copied)

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

important point

  1. The pre-order sequence simulated in this question is: 1 2 3 4 5 6
  2. The preamble sequence simulated in this question is: 3 2 4 1 6 5
  3. This question is similar to the previous question, adding an analog process, where the digital sequence pushed in is the preorder sequence, and the digital sequence popped out is the middle sequence
  4. Readers are recommended to simulate the create function
  5. It is more convenient to output the first, middle, and subsequent traversal methods by recursion, and the format is also very fixed, which can be written down
#include<bits/stdc++.h>
using namespace std;

const int maxn=30; 
int pre[maxn],in[maxn],post[maxn],n,num=0;
struct node{
	int data;
	node* lc;
	node* rc;
};
node* create(int prel,int prer,int inl,int inr){
	if(prel>prer)return NULL;
	node* root=new node;
	root->data=pre[prel];
	int k;
	for(k=inl;k<inr;k++){
		if(in[k]==pre[prel])break;
	}
	int numleft=k-inl;
	root->lc=create(prel+1,prel+numleft,inl,k-1);
	root->rc=create(prel+numleft+1,prer,k+1,inr);
	return root;
}
void postorder(node* root){
	if(root==NULL)return;
	postorder(root->lc);
	postorder(root->rc);
	printf("%d",root->data);
	num++;
	if(num<n)printf(" ");
}
int main(){
	int tmp,preindex=0,inindex=0;
	char a[5];
	stack<int> st;
	cin>>n;
	for(int i=0;i<2*n;i++){
		scanf("%s",a);
		if(strcmp(a,"Push")==0){
			scanf("%d",&tmp);
			pre[preindex++]=tmp;
			st.push(tmp);
		}else{
			in[inindex++]=st.top();
			st.pop();
		}
	}
	node* root=create(0,n-1,0,n-1);
	postorder(root);
    return 0;
}
Published 177 original articles · won praise 5 · Views 6673

Guess you like

Origin blog.csdn.net/a1920993165/article/details/105475736