03-树3 Tree Traversals Again

03-树3 Tree Traversals Again(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

用了一个enum顺利解决了问题

 1 #include<iostream>
 2 
 3 #include<stack>
 4 using namespace std;
 5 enum State{return_from_left,return_from_right};
 6 struct treenode{
 7 int data;
 8 treenode* left;
 9 treenode* right;
10 enum State state;
11 };
12 using tree=treenode*;
13 int tag=1;
14 void preordertraversal(tree st){
15 if(st){
16 preordertraversal(st->left);
17 preordertraversal(st->right);
18 if(tag--==1)
19     cout<<st->data;
20     else
21     cout<<" "<<st->data;
22 }
23 }
24 int main()
25 {
26 int N,data; cin>>N;
27 tree BT=new treenode();
28 stack<tree> s;
29 tree t,st;
30 st=BT;
31 string operation;  
32 cin>>operation>>data;
33 BT->data=data;
34 BT->state=return_from_left;
35 s.push(BT);
36     for(int i;i<2*N-1;i++){
37     cin>>operation; 
38     if(operation=="Push"){
39     cin>>data;
40     t=new treenode();
41     t->data=data;
42     t->state=return_from_left;
43     s.push(t);
44     if(BT->state==return_from_right)
45     BT->right=t;
46     if(BT->state==return_from_left)
47     BT->left=t;
48     BT=t;
49 }
50 if(operation=="Pop"){
51 BT=s.top();
52 s.pop();
53 BT->state=return_from_right;
54 }
55 }
56 preordertraversal(st);
57 }
View Code

 

 

posted @ 2017-12-18 09:05  A-Little-Nut  阅读(150)  评论(0编辑  收藏  举报