-
Notifications
You must be signed in to change notification settings - Fork 0
/
Parse.cpp
108 lines (99 loc) · 2.87 KB
/
Parse.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*构造解析树,假设字母表是Alphabet的26个字母
*/
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
using namespace std;
struct Node{
char data;
Node* left; //if *, only have left child
Node* right;
Node(): data('\0'), left(NULL), right(NULL){}
Node(char c): data(c), left(NULL), right(NULL) {}
Node(char c, Node* left_, Node* right_): data(c), left(left_), right(right_){}
};
class ParseTree{
public:
Node* Parse(string, int &);
void InOrderPrint(Node* root);
void LevelPrint(Node* root);
void Preprocess(string &s){
s += '$';
}
private:
Node* CreateNode(char data, Node* left, Node* right){
Node* root = new Node(data);
root->left = left;
root->right = right;
return root;
}
};
Node* ParseTree::Parse(string pattern, int &index){ //NOTICE: use int & here, cause index is global var.
Node* v = new Node();
while(pattern[index] != '$'){
char now = pattern[index];
if(isalpha(now)){
Node* vr = new Node(now);
if(v->data != '\0'){
v = CreateNode('.', v, vr);
} else {
v = vr;
}
//cout << now << endl;
++index;
} else if('|' == now){
Node* vr = Parse(pattern, ++index); //NOTICE: ++index NOT index+1
v = CreateNode('|', v, vr);
} else if('*' == now){
v = CreateNode('*', v, NULL);
++index;
} else if('(' == now){
Node* vr = Parse(pattern, ++index);
++index; //cause the Parse will return by ")", the index should go one more step to skip ")"
if(v->data != '\0'){
v = CreateNode('.', v, vr);
} else {
v = vr;
}
} else if(')' == now){
return v;
}
}
return v;
}
void ParseTree::InOrderPrint(Node* root){
if(!root) return;
InOrderPrint(root->left);
cout << root->data << " ";
InOrderPrint(root->right);
}
void ParseTree::LevelPrint(Node* root){
if(! root) return;
vector<Node*> vec;
vec.push_back(root);
int cur = 0;
int last = 0;
while(cur < vec.size()){ //BFS: iteration.
last = vec.size();
while(cur < last){ //The new layer
Node* node = vec[cur];
cout << node->data << " ";
if(node->left) vec.push_back(node->left);
if(node->right) vec.push_back(node->right);
++cur;
}
cout << endl;
}
}
int main(){
ParseTree parser;
string pattern("(AT|GA)((AG|AAA)*)");
parser.Preprocess(pattern);
cout << pattern << endl;
int index = 0;
Node* root = parser.Parse(pattern, index);
parser.InOrderPrint(root);
cout << endl;
parser.LevelPrint(root);
}