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 思路:本题出现意外,index不能再外面定义,在PAT OJ中定义会出现错误,另外本道题关于数学的知识有两点内容:1:有n个顶点,如果确定唯一一棵树的话进出栈的顺序次数是2*n2: 另外进栈的顺序是先序,出栈的顺序是中序。 这两点规律需要记住。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <stack> 5 using namespace std; 6 //定义静态链表 7 #define MAX 50 8 struct node 9 { 10 int data; 11 node* lchild; 12 node* rchild; 13 }; 14 int pre[MAX]; 15 int in[MAX]; 16 int post[MAX]; 17 int ind=0; 18 19 node * Create(int preL,int preR,int inL,int inR) 20 { 21 if(preL>preR) 22 return NULL; 23 node * root=new node; 24 root->data=pre[preL]; 25 int k; 26 for(k=inL;k<=inR;k++) 27 { 28 if(in[k]==root->data) 29 { 30 break; 31 } 32 } 33 int numleft=k-inL; 34 root->lchild=Create(preL+1,preL+numleft,inL,k-1); 35 root->rchild=Create(preL+numleft+1,preR,k+1,inR); 36 return root; 37 } 38 39 void Post(node * root) 40 { 41 if(root==NULL) 42 return ; 43 Post(root->lchild); 44 Post(root->rchild); 45 post[ind++]=root->data; 46 } 47 48 49 50 int main(int argc, char *argv[]) 51 { 52 node * root; 53 int n; 54 scanf("%d",&n); 55 stack<int>st; 56 char str[10]; 57 int prept=0,inpt=0; 58 for(int i=0;i<2*n;i++) 59 { 60 scanf("%s",str); 61 if(!strcmp(str,"Push")) 62 { 63 int number; 64 scanf("%d",&number); 65 st.push(number); 66 pre[prept++]=number; 67 } 68 else 69 { 70 int number=st.top(); 71 st.pop(); 72 in[inpt++]=number; 73 } 74 } 75 root=Create(0,n-1,0,n-1); 76 Post(root); 77 /* 78 for(int i=0;i<n;i++) 79 cout<<pre[i]<<" "; 80 cout<<endl; 81 for(int i=0;i<n;i++) 82 cout<<in[i]<<" "; 83 cout<<endl;*/ 84 for(int i=0;i<n;i++) 85 { 86 printf("%d",post[i]); 87 if(i<n-1) 88 putchar(‘ ‘); 89 } 90 putchar(‘\n‘); 91 return 0; 92 }