-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathONP.cpp
52 lines (43 loc) · 1.03 KB
/
ONP.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
/*
graphs > specials > tree
difficulty: medium
date: 04/Mar/2020
problem: infix to postfix conversion
hint: see that the given expression is the in-order traversal in a binary tree, then print post-order traversal recursively without building the tree
by: @brpapa
*/
#include <iostream>
using namespace std;
/*
(a+(b*c))
+
/ \
a *
/ \
b c
*/
bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/' || c == '^';
}
string exp;
string rpn(int l, int r) {
// substring [l .. r] de exp
if (l == r) return string(1, exp[l]);
int brackets = 0;
for (int k = l; k <= r; k++) {
if (exp[k] == '(') brackets++;
if (exp[k] == ')') brackets--;
if (brackets == 0 && isOperator(exp[k]))
return rpn(l, k-1) + rpn(k+1, r) + exp[k];
}
if (exp[l] == '(' && exp[r] == ')')
return rpn(l+1, r-1);
}
int main() {
int T; cin >> T;
while (T--) {
cin >> exp;
cout << rpn(0, exp.size()-1) << endl;
}
return 0;
}