-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1086_Tree_Traversals_Again.cpp
95 lines (82 loc) · 1.7 KB
/
1086_Tree_Traversals_Again.cpp
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
92
93
94
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string>
#include <sstream>
#include <stack>
using namespace std;
int N,cur;
vector<int> preOrder;
vector<int> inOrder;
typedef struct TreeNode *Node;
struct TreeNode{
int num;
Node left,right;
TreeNode(){
left = NULL;
right = NULL;
}
};
int findRootIndex(int rootNum){
for(int i = 0;i < N; i++){
if(inOrder[i] == rootNum){
return i;
}
}
return -1;
}
Node CreateTree(int left, int right){
if(left > right) return NULL;
int root = preOrder[cur];
cur++;
int rootIndex = findRootIndex(root);
Node T = new TreeNode();
T->num = root;
if(left != right){
T->left = CreateTree(left,rootIndex-1);
T->right = CreateTree(rootIndex+1,right);
}
return T;
}
bool firstOutPut = true;
void PostOrder(Node T){
if(!T) return;
PostOrder(T->left);
PostOrder(T->right);
if(firstOutPut){
printf("%d",T->num);
firstOutPut = false;
}else{
printf(" %d",T->num);
}
}
int main()
{
stringstream ss;
string Nstr;
getline(cin,Nstr);
ss << Nstr;
ss >> N;
ss.clear();
string input;
stack<int> stk;
int value;
for(int i = 0; i < N * 2; i++){
getline(cin,input);
if(input[1] == 'u'){
string num = input.substr(5);
ss << num;
ss >> value;
ss.clear();
stk.push(value);
preOrder.push_back(value);
}else{
value = stk.top();
stk.pop();
inOrder.push_back(value);
}
}
Node T = CreateTree(0,N-1);
PostOrder(T);
return 0;
}