-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexpression.cpp
More file actions
66 lines (63 loc) · 1.42 KB
/
expression.cpp
File metadata and controls
66 lines (63 loc) · 1.42 KB
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
#include <iostream>
#include <stack>
#include <string>
using namespace std;
struct Node {
char data;
Node* left;
Node* right;
Node(char value) {
data = value;
left = nullptr;
right = nullptr;
}
};
bool isoperator(char ch) {
return (ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '^');
}
Node* tree(const string& prefix) {
stack<Node*> st;
int n = prefix.length();
for (int i = n - 1; i >= 0; i--) {
if (isoperator(prefix[i])) {
Node* node = new Node(prefix[i]);
node->left = st.top(); st.pop();
node->right = st.top(); st.pop();
st.push(node);
} else {
st.push(new Node(prefix[i]));
}
}
return st.top();
}
void post(Node* root) {
if (!root) {
return;
}
stack<Node*> s1, s2;
s1.push(root);
while (!s1.empty()) {
Node* node = s1.top();
s1.pop();
s2.push(node);
if (node->left) {
s1.push(node->left);
}
if (node->right) {
s1.push(node->right);
}
}
while (!s2.empty()) {
cout << s2.top()->data << " ";
s2.pop();
}
cout << endl;
}
int main() {
string prefix;
cout<<"enter a prefix string to convert postoreder:";
cin>>prefix;
Node* root = tree(prefix);
post(root);
return 0;
}