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
|
#include <vector>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <climits>
#define nullInt INT_MIN
using namespace std;
void parseInput(string& input, vector<pair<int, string>>& pairs) {
for(auto& c : input) c = (c == '(' || c == ')') ? '"' : (c == ',') ? ' ' : c;
istringstream iss1(input);
string pairStr;
while(iss1 >> quoted(pairStr)) {
if(!pairStr.compare("")) break;
istringstream iss2(pairStr);
int idx;
string str;
iss2 >> idx >> str;
pairs.push_back({idx, str});
}
}
vector<int> createBinaryTree(vector<pair<int, string>>& pairs, int length) {
vector<int> binaryTree(length, nullInt);
for(auto & p : pairs) {
if(!p.second.compare("")) {
binaryTree[0] = p.first;
continue;
}
int idx = 0;
for(auto & c : p.second) idx = (idx << 1) + ( c == 'L' ? 1 : 2);
binaryTree[idx] = p.first;
}
return binaryTree;
}
bool checkBinaryTree(vector<int>& binaryTree, size_t branchLevel) {
if(binaryTree[0] == nullInt) return false;
// check each level
size_t left = binaryTree.size() - (1 << branchLevel);
size_t right = binaryTree.size();
for(size_t i(branchLevel); i > 0; --i) {
for(size_t j(left); j < right; ++j) {
if(binaryTree[j] != nullInt) { // check acestral node
int idx = (j-1) >> 1;
if(binaryTree[idx] == nullInt) return false;
}
}
left >>= 1;
right >>= 1;
}
return true;
}
void postOrderTraversal(const vector<int>& binTree, int index) {
if (index >= binTree.size()) return;
postOrderTraversal(binTree, 2 * index + 1);
postOrderTraversal(binTree, 2 * index + 2);
if(binTree[index] != nullInt) cout << binTree[index] << " ";
}
int main() {
string input;
while(getline(cin , input) && input != "()" && input != "") {
vector<pair<int, string>> pairs;
parseInput(input, pairs);
auto maxElement = std::max_element(pairs.begin(), pairs.end(), [](const auto& a, const auto& b) {
return a.second.length() < b.second.length();
});
vector<int> binaryTree = createBinaryTree(pairs, (1 << maxElement->second.length()+1) -1);
if(!checkBinaryTree(binaryTree, maxElement->second.length())) cout << "wrong data" << endl;
else {
postOrderTraversal(binaryTree, 0);
cout << endl;
}
}
return 0;
}
|