#include #include using namespace std; template struct Node{ T element; Node* left; Node* right; Node() : element(-1), left(nullptr), right(nullptr) {} Node(T x) : element(x), left(nullptr), right(nullptr) {} }; template struct Tree{ Node* root; Tree() : root(nullptr) {} Tree(Node* x) : root(x) {} void inOrder(Node* x){ if(!x) return; inOrder(x->left); cout << x->element << " "; inOrder(x->right); } void preOrder(Node* x){ if(!x) return; cout << x->element << " "; preOrder(x->left); preOrder(x->right); } void postOrder(Node* x){ if(!x) return; postOrder(x->left); postOrder(x->right); cout << x->element << " "; } }; bool checky(char s){ if(s == '+' || s == '-' || s == '*' || s == '/') return true; return false; } int checkb(char s){ if(s == '(') return 1; if(s == ')') return -1; return 0; } //[x, y) template Node* build(const string& s, const int& x, const int& y){ if ((y - x) == 1) return new Node(s[x]); // 去掉最外层括号 if (s[x] == '(' && s[y-1] == ')') { int cnt = 0; bool ok = true; for (int i = x; i < y; i++) { if (s[i] == '(') cnt++; if (s[i] == ')') cnt--; if (cnt == 0 && i < y-1) { ok = false; break; } } if (ok) return build(s, x+1, y-1); } // 两次扫描:先 +-,再 */ for (int pass = 0; pass < 2; pass++) { int js = 0; for (int i = y-1; i >= x; i--) { js += checkb(s[i]); if (checky(s[i]) && js == 0) { if ((pass == 0 && (s[i] == '+' || s[i] == '-')) || (pass == 1 && (s[i] == '*' || s[i] == '/'))) { Node* tmp = new Node(s[i]); tmp->right = build(s, i+1, y); tmp->left = build(s, x, i); return tmp; } } } } return nullptr; } int main(){ string a; cin >> a; Node* root = build(a, 0, a.size()); Tree t(root); t.preOrder(root); cout << endl; t.inOrder(root); cout << endl; t.postOrder(root); cout << endl; return 0; }