This commit is contained in:
e2hang
2025-09-16 23:10:48 +08:00
parent e9519e8558
commit 24522486f1
10 changed files with 249 additions and 0 deletions

View File

@@ -0,0 +1,100 @@
#include <iostream>
#include <string>
using namespace std;
template <class T>
struct Node{
T element;
Node<T>* left;
Node<T>* right;
Node() : element(-1), left(nullptr), right(nullptr) {}
Node(T x) : element(x), left(nullptr), right(nullptr) {}
};
template <class T>
struct Tree{
Node<T>* root;
Tree() : root(nullptr) {}
Tree(Node<T>* x) : root(x) {}
void inOrder(Node<T>* x){
if(!x) return;
inOrder(x->left);
cout << x->element << " ";
inOrder(x->right);
}
void preOrder(Node<T>* x){
if(!x) return;
cout << x->element << " ";
preOrder(x->left);
preOrder(x->right);
}
void postOrder(Node<T>* 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 <class T>
Node<T>* build(const string& s, const int& x, const int& y){
if ((y - x) == 1) return new Node<T>(s[x]);
// ȥ<><C8A5><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
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<T>(s, x+1, y-1);
}
// <20><><EFBFBD><EFBFBD>ɨ<EFBFBD><EFBFBD><E8A3BA> +-<2D><><EFBFBD><EFBFBD> */
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<T>* tmp = new Node<T>(s[i]);
tmp->right = build<T>(s, i+1, y);
tmp->left = build<T>(s, x, i);
return tmp;
}
}
}
}
return nullptr;
}
int main(){
string a;
cin >> a;
Node<char>* root = build<char>(a, 0, a.size());
Tree<char> t(root);
t.preOrder(root);
cout << endl;
t.inOrder(root);
cout << endl;
t.postOrder(root);
cout << endl;
return 0;
}