Altered
This commit is contained in:
100
Algorithm/Graph/Tree/表达式树/后缀分治.cpp
Normal file
100
Algorithm/Graph/Tree/表达式树/后缀分治.cpp
Normal 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;
|
||||
}
|
||||
Reference in New Issue
Block a user