pat 1086 tree travel again

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#define MAX 30
#define NULL 0
using namespace std;
struct node
{
int data;
node* lchild;
node* rchild;
};
int N;
int pre[MAX] , in[MAX];
node* create(int preL , int preR , int inL , int inR)
{
if(preL > preR)
return NULL;
node* root = new node;
root->data = pre[preL];
int k;
for(k = inL ; k <= inR ; ++k)
{
if(in[k] == pre[preL])
break;
}
int numLeft = k - inL;
root->lchild = create(preL+1 , preL+numLeft , inL , k-1);
root->rchild = create(preL+numLeft+1 , preR , k+1 , inR);
return root;
}
bool flag = true;
void postOrder(node* root)
{
if(root)
{
postOrder(root->lchild);
postOrder(root->rchild);
if(flag)
{
cout<<root->data;
flag = false;
}
else
cout<<" "<<root->data;
}
}
int main()
{
cin>>N;
int i , j = 0 , k = 0;
stack<int> s;
for(i = 0 ; i < 2*N ; ++i)
{
string op;
int data;
cin>>op;
if(op == "Push")
{
cin>>data;
s.push(data);
pre[j++] = data;
}
if(op == "Pop")
{
in[k++] = s.top();
s.pop();
}
}
node * root = create(0 , N-1 , 0 , N-1);
postOrder(root);
return 0;
}

热评文章