1086. Tree Traversals Again

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.

#include <stdio.h>#include <stdlib.h>#include <string.h>#include <vector>using namespace std;typedef struct Node{int data;struct Node * left,* right;}Node;char push[]="Push",pop[]="Pop";vector<int> pre,in,post;int n;void Post (Node * root,vector<int> &post);Node * Creat (int ps,int pe,int is,int ie);int main (){int i;scanf("%d",&n);char temp[5];int id;int *stack=new int[n],top=0;for( i=0;i<2*n;i++){scanf("%s",temp);if( strcmp(temp,push)==0)//push{scanf("%d",&id);pre.push_back(id);stack[top++]=id;}else//pop{id=stack[–top];in.push_back(id);}}Node *root=Creat(0,n-1,0,n-1);Post(root,post);printf("%d",post[0]);for( i=1;i<post.size();i++) printf(" %d",post[i]);system("pause");return 0;}void Post (Node * root,vector<int> &post){if( root==NULL) return ;Post(root->left,post);Post(root->right,post);post.push_back(root->data);}Node * Creat (int ps,int pe,int is,int ie){if( ps>pe || is>ie) return NULL;int temp=pre[ps],i;Node * root=new Node;root->data=temp;for( i=is;i<=ie;i++) if( in[i]==temp) break;root->left=Creat(ps+1,ps+i-is,is,i-1);root->right=Creat(ps+i-is+1,pe,i+1,ie);return root;}

,或许是某个未开发的荒凉小岛,或许是某座闻名遐迩的文化古城。

1086. Tree Traversals Again

相关文章:

你感兴趣的文章:

标签云: