码迷,mamicode.com
首页 > 其他好文 > 详细

03-树3 Tree Traversals Again

时间:2017-12-18 12:34:44      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:space   mod   html   class   order   des   ring   ant   sequence   

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

 

 

03-树3 Tree Traversals Again

标签:space   mod   html   class   order   des   ring   ant   sequence   

原文地址:http://www.cnblogs.com/A-Little-Nut/p/8056051.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!