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.1
2
3
4
5
6
7
8
9
10
11
12
13
14Sample Input:
6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop
解题思路
先序遍历序列是push的顺序
中序遍历序列是pop的顺序
先序:先中间后左右(中左右)
中序:先左后中再右(左中右)
在中序序列中找根节点(中间元素) 再递归左右建立二叉树1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64#include<bits/stdc++.h>
using namespace std;
#define MAX 50
stack<int> st;
int n;
int pre[MAX],mid[MAX];
struct node{
int data;
node *l,*r;
};
node* create(int preL,int preR,int inL,int inR){
//递归要有终止条件
if(preL>preR){
return NULL;//!
}
node *head=(node*)malloc(sizeof(node));
head->data=pre[preL];
int k;
for(int i=inL;i<=inR;i++){
if(mid[i]==pre[preL]){
k=i;
break;
}
}
int numl=k-inL;
head->l=create(preL+1,preL+numl,inL,k-1);
head->r=create(preL+numl+1,preR,k+1,inR);
return head;
}
int num=0;
void postorder(node *root){
if(root==NULL) return;
postorder(root->l);
postorder(root->r);
num++;
cout<<root->data;
if(num<n) cout<<" ";
}
int main(){
cin>>n;
char str[20];
int pind=0,zind=0,x;
for(int i=0;i<2*n;i++){
scanf("%s",str);
if(strcmp(str,"Push")==0){
scanf("%d",&x);
pre[pind++]=x;
st.push(x);
}
else{
// scanf("%d",&x);
mid[zind++]=st.top();
st.pop();
}
}
// node * root=create(0,pind-1,0,zind-1);!
node * root=create(0,n-1,0,n-1);
postorder(root);
}